Does the keyword final have any impact on the JVM? [duplicate] - java

This question already has answers here:
Does use of final keyword in Java improve the performance?
(14 answers)
Closed 7 years ago.
Now, I recently ran into a recommendation that you should use the keyword final as wide as possible. This is good in order to prevent a programmer from shooting his own leg - that is, reassign the variable that should not be reassigned.
But, does it serve any other goal? That is, can JVM use information about the final variables in order to optimize the bytecode somehow, so it would ran faster (build a better pipelining or use it in a multithreaded environment)? Or is just a syntactic sugar that minimizes the possibility of errors during code development?

IBM states:
Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.

As far as variables go, Java is smart enough to figure that a variable is not being changed anywhere in the method, and use this knowledge for optimization purposes. It does not need you to mark a variable final in order to know that.
Methods are a slightly different story: when you mark a method final, Java can invoke such method faster, because it no longer needs to check for its overrides. Still, hotspot is smart enough to figure out that there are no overrides, with or without the use of final.
Generally, though, this recommendation is intended to make your code easier to read and understand by others: making a variable final tells you readers that you are making a constant; making a class final tells your readers that the class is not designed for inheritance; making a method final tells your readers that the logic of that method should stay invariant across the inheritance hierarchy. In the long run, this information is more valuable than the potential to optimize your running code.

I think this recommendation is a bit too unspecific.
For example; I would recommend to avoid using final on classes and methods by default (because final classes break unit tests, respectively force you to use specific unit test frameworks to overcome final methods/classes).
I also find that using final for method parameters is just a waste of "screen space" (and thus: wasting "energy" on the side of the reader).
On the other hand, having only final attributes for classes can turn objects of such classes into immutable thingies; and that is a good thing.
As you see; there are many pros and cons on the usage of final; and I think that "readability" most often wins over "potential" performance improvements.

final methods may or may not be inlined by the JVM until they after they are loaded by the JVM. So, if you're sure the method is not going to be redefined, mark it as final.
Constants should always be static final since they will be immutable and jvm does not need to keep track of these variables since they will never change.

Related

What kind of optimization does `final` enable? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Does use of final keyword in Java improve the performance?
So there's a class-level object variable that's allocated upon object creation and stays put for the lifetime of the object:
class MyClass
{
private Rect rc = new Rect();
//...
}
What do I gain be declaring it final? Same question for method-level variables.
it is all completely implementation specific.
main reason to use final is to ensure that variable value is not allowed to be change over time. it's a matter of you code logic and not optimization.
Declaring variables final does have benefits that come from immutability. If used properly your code can be more thread safe, provided the variable you're making final does not have internal state that could be changed unexpectedly and effect other threads.
See the other answers here too about JVM optimizations.
Final has one obvious use, where it makes the object/variable immutable, now can this feature help in performance gains?
Quoting: The Final Word On the final Keyword, the performance gain you get using final is:
A field doesn't need to be ever reloaded, since its value is
guaranteed never to change.
But I see a flaw in the above statement, the value won't be reloaded if it's set only once and final guarantees that it will never be reloaded again, but this does not mean using final directly helps you in performance gain, the performance gain we get here is due to the property that if we make sure we do not set the to something else, it will anyway, won't be reloaded.
So, you answer:
Although, it is implementation specific to the JVM and atleast in the HotSpot, you will get no performance gains from using final. Read more: Does use of final keyword in Java improve the performance?
IBM also says you won't get ant performance gain out of final.
This might not give you 100% answer. But i have a point which i know.
There is lot of optimization gained by the jvm when you declare variables as final.
I remember a good example where i have if-else conditions in my program and in the condition since i used final variable, complier has evaluted which part of if-else is valid and it stripped out the other lines and i have seen it with javap. I will get you that example soon.
It allows for some optimization via memoization. For example, if you have a Rectangle class with final height and final width, then your rectangle's area function only needs to compute it once, since it knows that height and width cannot change.
I doubt that final fields have a hughe impact on performance, unless you have shared object in multiple threads.
However declaring methods final or even classes will help the jit to determine wether a method can be overridden, or can't. If the jit is certain the method is no where overwritten he might remove the method lookup and use a direct jump (jump subroutine). Also Jits like to inline small final methods.
Besides the obvious compile-time protection from modifications (*) you do gain some form of optimized access to its value. The compiler may for example replace the references of primitive variables with literal values. The runtime can for example place copies of the its content in each thread's private memory space to avoid accessing main memory. It does depend on each JVM implementation.
For local variables you do again have gains, both at compile-time and at run-time, mostly in the form of thread-access optimizations. Bear in mind though, that you will only ever notice these gains in hot spots of your code, code that executes hundreds or thousands of times per second.
(*) final only protects from compile-time modifications after the introduction of Accessible Objects.

Java optimizations: (Hotspot/Dalvik) Optimization of final method returning a constant?

Can anyone tell me if either Hotspot or Dalvik is smart enough to inline calls to a final method returning a constant (static final) int value? Ideally the method call would be replaced by the constant. This might either be at class load time or through JIT.
This has implications in the design of some code I'm working on.
I would think that the answer is "no, optimization will not happen because of absence or presence of the final keyword", at least on the HotSpot VM. But optimization will likely happen because of other factors.
Here's what Brian Goetz says in this article (sorry for the long quote):
Like many myths about Java performance, the erroneous belief that
declaring classes or methods as final results in better performance is
widely held but rarely examined. The argument goes that declaring a
method or class as final means that the compiler can inline method
calls more aggressively, because it knows that at run time this is
definitely the version of the method that's going to be called. But
this is simply not true. Just because class X is compiled against
final class Y doesn't mean that the same version of class Y will be
loaded at run time. So the compiler cannot inline such cross-class
method calls safely, final or not. Only if a method is private can the
compiler inline it freely, and in that case, the final keyword would
be redundant.
On the other hand, the run-time environment and JIT compiler have more
information about what classes are actually loaded, and can make much
better optimization decisions than the compiler can. If the run-time
environment knows that no classes are loaded that extend Y, then it
can safely inline calls to methods of Y, regardless of whether Y is
final (as long as it can invalidate such JIT-compiled code if a
subclass of Y is later loaded). So the reality is that while final
might be a useful hint to a dumb run-time optimizer that doesn't
perform any global dependency analysis, its use doesn't actually
enable very many compile-time optimizations, and is not needed by a
smart JIT to perform run-time optimizations.
There's also a good post why final is not final any more, at least in Java 5.
Inlining is something the JIT compiler might do if it detects a hot spot, a method in the byte code that has been called that often that it probably worth spending some CPU time on compiling the byte code into machine code.
There's a very good chance that the JIT compiler will inline a final method (as it can't be overwritten). And chances will be even better if that method just returns a constant value.
But it's my understanding - if the calling method is not a hot spot, then it will not be compiled and there'll be no inlining of the final methods.
(Information source in german language)
Alternatively, Soot is expected to optimize Java bytecode for such case.

Always Use Final?

I have read that making something final and then using it in a loop will bring better performance, but is it good for everything? I have lots of places where there isnt a loop but I add final to the local variables. Does it make it slower or is it still good?
Also there are some places where I have a global variable final (e.g. android paint), does it mean I don't have to make it a local final when using it in loops?
The first thing you should consider is; What is the simplest and clearest way I can write this code. Often this performs well.
final local variables is unlikely to affect performance much. They can help clarity when you have long methods, but I would suggest breaking up method is a better approach.
final fields can affect performance to small degree, but a better reason to make it final is to make it clear that this field never changes (which also helps the JIT)
Don't think about performance. final on object member (fields) have significant memory semantics that may improve performance (but more importantly, its often necessary to make the code correctly work at all). You should always put final on object members whenever you can. For local variables however, you should only use it if it will improve code readerability, or can prevent bugs when a maintainer touches your code.
The general consensus of the Java community is that final on every local variables will make the code difficult to read. On the performance front, you can expect no optimization as local variables are easy to analyze for the compiler. In other words, the compiler can figure it out by itself.
From my experience most variables could be declared final.
However, it looks very ugly. That is my main point against it.
And if the part of the program is not performance critical, beware of premature optimization.
It's considered good form to use final where possible (for fields and variables, not classes and methods), if for no other reason than it makes testing easier. Final will never have a negative impact on performance.
Here are my 2 cents:
Use final on attributes to minimize mutability and for documentation purposes, only use final on local variables if they are used in inner/anonymous classes.
DON'T use it for microoptimizations! Especially don't use them on classes or methods because you think it will improve performance. Make classes and methods final to prohibit inheritance or overriding methods.
Final on attributes should not have any impact on performance. Except: in a multi threaded environment where several threads access the same field and "don't know" if they have to relaod it. Final on local variables has no impact at all, as nothing except the local scope can access them anyway.
Final on methods can have an impact during JIT compiling. If a method is final and small the compiler can inline it in loops, as it is clear that no one will have overwritten it.
I usually don't use final on attributes at all, as final attributes can not be loaded from DBs easily etc. Declaring pararameters to methods final lokos ugly (I never assign to them inside my code anyway) but might prevent simple bugs comming from typoes. However if you start using proper names for your variables you unliek make such typoes.
Theoretically, if you make a local variable final it can be optimized. I don't think making them final yourself really improves performance though, because the optimizer probably already detects when your locals don't change. That said, it can't hurt to help it a bit.
In some situations, it would help to change one variable into two, e.g. from this
String a = "foo";
if (lol) a += "bar";
for(.. 1000 ...) doSomething(a);
to
final String a;
{
String ma = "foo";
if (lol) ma += "bar";
a = ma;
}
for(.. 1000 ...) doSomething(a);
Disclaimer: I'm not a JIT expert.
Final variables are constants, therefore the compiler could generate constant value instead of variable referencing instruction. Of course that would improve speed (and commonly size as well).
Also there are some places where I have a global variable final (e.g. android paint), does it mean I don't have to make it a local final when using it in loops?
Sorry, do you mean you don't have to:
final int somefinalvalue = 0;
void amethod() {
final int somefinalvalue = 0; // repeated from global one
}
or what? remember that if you declare local variable which has the same name as global one, that would 'shadow' the global one. i.e. it's actually a totally different variable. if you already have the global one, just use that. no need to re-declare.
I don't think this should be your first concern, as mentioned by #perter-lawrey. First, compiler optimization can very much do the trick; second, there are some tools that can analyze your generated class files and do the same thing, for example, ProGuard: java shrinker, optimizer, obfuscator, and preverifier.

Why are local variables not declared final in most open source java projects?

If I look at the java source source code in the OpenJDK or Hibernate or Apache I have yet to see any local variables declared final.
This suggests that the developers of some of the most widely used java software libraries:
do not believe the final keyword improves readablity.
do not believe it significantly improves performance.
Why do the majority of contrbuters on stackoverflow believe it it should be used (based on the highest voted responses)?
Probably because it's a hassle to type in the five LONG letters in the word final... why would they go through the pain of writing
final int x;
when it's twice as much typing as
int x;
?
We developers are lazy, you know... :P
do not believe the final keyword
improves readablity.
Some people (such as myself) find excessive finals decreases readability.
do not believe it significantly
improves performance.
final local variables does not improve performance.
As far as I'm aware, the final keyword has no impact on the runtime performance of your variables.
I believe it's primary purpose is to assist you in the catching of bugs. If you know something is never going to change, you mark it as such. Similar to why we use annotations where we can, any time we can trade a runtime bug for a compile time error, we do. Finding an error when you're working on it, and it's fresh in your mind, and it hasn't gone and corrupted someone's data causing you to lose customers, yeah that's a very good thing. You get the compile error, you fix it, you move on, you don't break the nightly build, yeah those are good things.
The final keyword has two uses:
declare a class or method as final in order to prevent subclassing/overrding
declare a variable as final in order to prevent changing it (assigning a new value)
Case 2 is normally applied to member variables in order to make the object immutable (at least partly) or to method parameters in order to prevent accidential assignments.
In case of a local variable (i.e. method scoped and not a parameter), that's normally not necessary or wanted, since those variables are likely to be changed within the method (otherwise you might not need them, except to cache a reference for method scope).
I doubt declaring a local variable final ever improves performance. By virtue of the existence of final, Java compilers are already required to be able to tell if a variable might be assigned more than once, or might not be initialized. Therefore, actually declaring a local as final doesn't tell the compiler anything it didn't already know--it's only for the benefit of the reader.
Now whether it sometimes improves readability, that's more subjective. In a complicated piece of code it can be nice to promise (to yourself, or to future readers) that a variable is only written once. But it might be nicer to simplify the code so that is readily apparent anyway.

Java super-tuning, a few questions

Before I ask my question can I please ask not to get a lecture about optimising for no reason.
Consider the following questions purely academic.
I've been thinking about the efficiency of accesses between root (ie often used and often accessing each other) classes in Java, but this applies to most OO languages/compilers. The fastest way (I'm guessing) that you could access something in Java would be a static final reference. Theoretically, since that reference is available during loading, a good JIT compiler would remove the need to do any reference lookup to access the variable and point any accesses to that variable straight to a constant address. Perhaps for security reasons it doesn't work that way anyway, but bear with me...
Say I've decided that there are some order of operations problems or some arguments to pass at startup that means I can't have a static final reference, even if I were to go to the trouble of having each class construct the other as is recommended to get Java classes to have static final references to each other. Another reason I might not want to do this would be... oh, say, just for example, that I was providing platform specific implementations of some of these classes. ;-)
Now I'm left with two obvious choices. I can have my classes know about each other with a static reference (on some system hub class), which is set after constructing all classes (during which I mandate that they cannot access each other yet, thus doing away with order of operations problems at least during construction). On the other hand, the classes could have instance final references to each other, were I now to decide that sorting out the order of operations was important or could be made the responsibility of the person passing the args - or more to the point, providing platform specific implementations of these classes we want to have referencing each other.
A static variable means you don't have to look up the location of the variable wrt to the class it belongs to, saving you one operation. A final variable means you don't have to look up the value at all but it does have to belong to your class, so you save 'one operation'. OK I know I'm really handwaving now!
Then something else occurred to me: I could have static final stub classes, kind of like a wacky interface where each call was relegated to an 'impl' which can just extend the stub. The performance hit then would be the double function call required to run the functions and possibly I guess you can't declare your methods final anymore. I hypothesised that perhaps those could be inlined if they were appropriately declared, then gave up as I realised I would then have to think about whether or not the references to the 'impl's could be made static, or final, or...
So which of the three would turn out fastest? :-)
Any other thoughts on lowering frequent-access overheads or even other ways of hinting performance to the JIT compiler?
UPDATE: After running several hours of test of various things and reading http://www.ibm.com/developerworks/java/library/j-jtp02225.html I've found that most things you would normally look at when tuning e.g. C++ go out the window completely with the JIT compiler. I've seen it run 30 seconds of calculations once, twice, and on the third (and subsequent) runs decide "Hey, you aren't reading the result of that calculation, so I'm not running it!".
FWIW you can test data structures and I was able to develop an arraylist implementation that was more performant for my needs using a microbenchmark. The access patterns must have been random enough to keep the compiler guessing, but it still worked out how to better implement a generic-ified growing array with my simpler and more tuned code.
As far as the test here was concerned, I simply could not get a benchmark result! My simple test of calling a function and reading a variable from a final vs non-final object reference revealed more about the JIT than the JVM's access patterns. Unbelievably, calling the same function on the same object at different places in the method changes the time taken by a factor of FOUR!
As the guy in the IBM article says, the only way to test an optimisation is in-situ.
Thanks to everyone who pointed me along the way.
Its worth noting that static fields are stored in a special per-class object which contains the static fields for that class. Using static fields instead of object fields are unlikely to be any faster.
See the update, I answered my own question by doing some benchmarking, and found that there are far greater gains in unexpected areas and that performance for simple operations like referencing members is comparable on most modern systems where performance is limited more by memory bandwidth than CPU cycles.
Assuming you found a way to reliably profile your application, keep in mind that it will all go out the window should you switch to another jdk impl (IBM to Sun to OpenJDK etc), or even upgrade version on your existing JVM.
The reason you are having trouble, and would likely have different results with different JVM impls lies in the Java spec - is explicitly states that it does not define optimizations and leaves it to each implementation to optimize (or not) in any way so long as execution behavior is unchanged by the optimization.

Categories