Question

Please consider the following context (It is a snippet of Android code)

TextView tvTitle = findViewById(R.id.something);
// do stuff with 'tvtitle'

In this context suppose both final declaration and non-final declaration is okay and works fine.

My question is: Is there any performance advantage in declaring variables as final or not? I've seen in many places in codes that normal variables is defined as final. I know what the final key word does but I do not know performance consideration about this.

Any help would be highly appreciated. Thanks

Was it helpful?

Solution 2

The Java compiler is perfectly able to determine which variables are being changed and which are not (thus being able to enforce something like final in the first place).

There is no performance advantage to declaring final for local variables yourself. The only advantages are developer ones, e.g. being able to know that a variable doesn't change, and have the compiler verify this for you.


Note: There can be advantages in final non-private methods, classes, and member variables. This provides information the compiler cannot know only from that source code. (Actual effectiveness may vary.)

OTHER TIPS

It depends on the JVM implemenation. With a final variable, the java virtual machine is free to bypass certain checks and operations that would be needed to ensure strictly correct execution for a non-final variable.

JVMs will implicitly final local variables not written to. They cannot do this for fields that are not private, as another class could be loaded that would write to them.

You should also consider that declaring a variable final where it should be helps prevent bugs that may occur where you try to write to it. Your compiler will be able to catch them sooner in this case.

All in all, for a sane JVM, it wouldn't hurt to declare as final.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top