Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

String用final修饰的真正原因 #2462

Open
kiritozc opened this issue Aug 25, 2024 · 2 comments
Open

String用final修饰的真正原因 #2462

kiritozc opened this issue Aug 25, 2024 · 2 comments
Labels
discuss discuss a problem

Comments

@kiritozc
Copy link

kiritozc commented Aug 25, 2024

JavaGuide中提到String用final修饰是为了避免被继承后修改String的值,导致破坏String的不可变性。

实际上只需要使用private修饰byte[]数组即可保证String的不可变性,String使用final修饰的真正原因是加速String方法的调用过程
在Java中存在着虚函数表,虚函数表的主要作用是帮助多态加速。具体来说,在编译时每个类都会生成一张虚函数表,记录着所有方法的指针。在运行时,通过实例对象的真正类型,找到虚函数表,再获得需要调用的方法的指针。这是一个动态的过程(因为需要在运行时确定方法的指针)。
而如果一个类被final修饰,那么我们在编译时即可确定对象的运行时类型(因为没有子类,自然也不用考虑多态),因此可以在编译时就确定方法指针,无需动态获取,提高了运行速度。

@liach
Copy link

liach commented Nov 6, 2024

final更是为了安全,不然来个子类覆写charAt这些方法返回一些异常值,或者toCharArray返回子类可以保留引用的数组等等问题。反例是AbstractMap.SimpleImmutableEntry因为非final所以获得此对象后返回的key value不一定final;子类可以重新实现setValue getValue。

@Snailclimb Snailclimb added the discuss discuss a problem label Nov 8, 2024
@freeok
Copy link

freeok commented Jan 21, 2025

  • 在现代 JVM 中,JIT 编译器已经非常智能,对于非 final 的类和方法,JVM 也可以通过动态分析优化方法调用的性能(如内联)
  • 使用 final 更多是为了 语义清晰性代码的安全性,而非直接提升性能

Image

https://www.baeldung-cn.com/java-final-performance#5-classes-and-methods

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
discuss discuss a problem
Projects
None yet
Development

No branches or pull requests

4 participants