如果它没有在代码中修改,我应该声明一个java字段'final'吗?
我的问题主要是关于表现。编译器知道更好,例如,在对象实例化之后不修改某个变量。那么,为什么要打扰决赛?
My question is mainly about performance. The compiler knows better that, for example, some variable is NOT modified after object instantiation. So, why bother with final?
我认为很多结构/逻辑原因可能会出现在这里,但从性能的角度来看呢?这有关系吗?
I presume many structural/logical reasons might come here, but speaking from the performance point of view? Does it matter?
谢谢,
在现代 JVM,最终不应该影响性能。对于私有字段尤其如此,但即使对于非私有字段,JIT也可以优化非最终字段,因为它们是最终的,然后 deoptimize 如果它加载了一些实际修改字段的代码。
In a modern JVM, final shouldn't affect performance. This is especially true for private fields, but even for non-private fields the JIT can optimize non-final fields as thought they are final, and then deoptimize if it loads some code that actually does modify the field.
那就是说,使用final的主要原因不是性能,但要使您的代码更易于维护。通过最终制作字段,您可以减少代码中移动部件读取器的数量,从而更容易推理代码。
That said, the main reason to use final is not performance, but to make your code more maintainable. By making fields final you are reducing the number of "moving parts" readers of your code have to think about, making it much easier to reason about the code.