Thursday, November 29, 2007

Performance - Final Keyword ?

Last night, me and Abhishek was discussing about some performance issue. Finally we came on a good conclusion and so I decided to write a blog. One of the Orkut users posted a question on our community

"As we know that by declaring method as final, we cant override them..........By performing this function, it provides a performance enhancement.........but i unable to understand how??????????? can anyone help me out...... "

(I don't know why people are using so many of dots and question marks)

Yes this is correct, writing final (can) improve the performance. Straight away question - WHY ?
When you define a method final, that means it can't be overridden into its derived classes. Knowing that into the fact complier (can) inline that method into its derived classes. But but but, this is not a safe way to inline a method. WHY AGAIN ?
Because, if by any chance if method will not be final (fool the VM) in base class, then inline entry in derived class will be wrong and things can be screwed. Now very rare but this is possible in Java. Remember in Java you can write your own classLoader and you can make a classLoader where you can ignore(any how) the final declaration.
So, for those compiler in which final method be inlined before loaded into VM(unlike JIT), there is quite a high risk and hence compiler can't do this. But in JIT compiler, this is what is happening ! (If you want to know more about JIT, please let me know :) ).

And this is how we finally ended our discussion :)