• Post Reply Bookmark Topic Watch Topic
  • New Topic

Keyword Final & Performance

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read in Murach's Java SE 6 that using the keyword final on a class or method or variable results in minor performance improvement.

The given reason is that since the compiler does not have to allow for inheritance or polymorphism, it generates more efficient code.

Does anybody have any additional thoughts on this.
 
Jimmy Clark
Ranch Hand
Posts: 2187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The given reason is that since the compiler does not have to allow for inheritance or polymorphism, it generates more efficient code.


The efficiences of using final on methods are visible in runtime execution of code. When a method is about to execute in the JRE, there is a check to see what object type it is, are there any subclasses, overriden methods and what method should be called.

This invloves overhead. This is why static methods execute faster than non-static methods. When methods are declard final, their runtime is similar to static methods. The non-static equivalent is about three times more expensive.

Whenever possible, it is best to use final qualifiers on methods.
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Victor,

The key term here is "minor."

Since premature optimization is the root of all evil, don't use "final" because you might get a performance benefit.

Use final when it makes sense for better code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!