Use of final keyword in Java method performance? [duplicate]

蓝咒 提交于 2019-12-06 03:12:26

Theoretically, declaring a parameter final is not going to make a difference: the compiler is allowed to be smart enough to figure out that your method does not change the limit parameter, and optimize the code that it generates as if the parameter were declared final without the actual declaration.

The biggest difference that you are going to get by declaring method parameter final is the ability to reference that parameter in anonymous classes.

Another useful consequence is that people who maintain your code after you would know that keeping that parameter unchanged was your conscious decision, not a coincidence.

The current java compilers do already a good data flow analysis, it is a statement of having a non-alterable parameter. Only dumb compilers could have some use for this.

For a reader however it is a good hint. And code is written once, read often.

In general it is enforced by some style guides, saying "a parameter should never be overwritten".

A better reason is the usage in an inner class, as there the method context requires parameters and local variables to be final.

However a final method; one that cannot be overriden has optimizing potential.

public final int isLargerAfterTripled(int num, int limit) { ... }

The compiler may inline the function code, as the method will never be overriden.

final has absolutely no impact on performance. The JIT compiler does not consider final at all.

Also take a look at Brian Goetz's article on Java final.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!