Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Most languages support one or two of these. Java uses table dispatch by default, but you can opt into direct dispatch by using the final keyword.

This is not accurate. Java does not use table dispatch by default. The HotSpot compiler will optimize most code to use direct dispatch, reserving table dispatch only for cases where calls cannot be inlined; and final does not particularly enable direct dispatch.

A discussion of these issues: http://www.ibm.com/developerworks/java/library/j-jtp1029/ind...

> 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.



> 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.

Yes, was about to point this out, one of the more resilient misconceptions about Java. I've lost count of how many times I had to explain this and remove a boatload of unnecessary "final".


I should been clearer, I was referring to the pre-JIT behavior. Definitely an important distinction!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: