Can really "final" classes/methods be sometimes more efficient?

Alexandre's icon

I'm curious about this in my java book (translation) :

"With its perfectly defined nature, a final method permit for the compiler :
- to optimise some parts of the code: faster calls because independent from the execution, to put 'online' the code of some methods..."

I tried a little efficiency test over a small method call inside a java loop, with or without final, but it's the same. True that my test might be too simple.

Can really "final" classes/methods be sometimes more efficient?
But even without knowing about the amount of speed gain, we should anyway set all our mxj objects to "final", no ?

Alexandre's icon

No idea anyone ?

Brian Gruber's icon

The short answer is: No. We shouldn't be making everything final. Like most performance questions, the old adages apply: "premature optimization is the root of all evil," and "talking about performance without actual data is a very fast way to sound stupid." So let's get to sounding stupid.

There are essentially three types of things that can be set as 'final' in Java:
- classes
- methods
- values

Making a method final can have some impact; it enables the JVM to eliminate table-lookups to determine which method is really being called. However, given even the little that I know about how HotSpot (the JVM used by basically everybody), this would probably be optimized away anyhow. There are some instances where I could see it making a difference, but they would be very specialized.

Making a class final is, for these purposes, basically a shorthand for making all of the methods final, so the effects are the same.

On the other hand, making variables final could have a big impact on performance if you really made all of your members final and didn't do any sort of mutation whatsoever. However, this would have wide-reaching implications about how your code works. Rich Hickey, the inventor of Clojure, a Lisp that runs on the JVM and pushes a functional programming style, actually started out by writing java classes where everything is final. He knew exactly what he was dong though, and knows an awful lot about functional programming and immutable, persistent data structures.

If you can make some stuff in your code final, go ahead. You probably won't see much of an impact on performance. If you do, great.

Alexandre's icon

Thanks for tips, Brian !