Question

Is there any performance gain from using final modifier on non-primitive static data in Java?

For example:

static final Thread t2 = new Thread(new Thread_2());

versus:

static Thread t2 = new Thread(new Thread_2());

I mean, static final for primitives defines a true constant and is good to be used, in the sense that it's value is known at compile time, but could the use of final trigger any optimizations in this non-primitive case?

Does using final in this case does something or it's a waste?

Not style-wise/good practice answers please, but performance-wise only.

Was it helpful?

Solution

The JVM can make some optimizations if it knows a value will never change (for example, disabling null checks), so it will lead to some small performance gain. In almost all circumstances, though, this gain will be too small to notice or worry about. I don't know much about your program, but I would guess that time spent making variables final would be better spent on developing a more efficient algorithm.

OTHER TIPS

While there can be a small performance gain, and some static final values will be embedded in the class in which they are used, to my mind the biggest benefit is from the compiler enforcing the intent & design that the value does not change - that is, the gain is to the developer(s).

And in my way of thinking, skeleton/framework code should be the best it can be in every way, not just performance, but stylistically too.

I would encourage you to declare everything as final unless it has a real need to be mutable - that is, things are final by default, unless needed to be otherwise.

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