• Post Reply Bookmark Topic Watch Topic
  • New Topic

Final Variable  RSS feed

 
sam liya
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is that says when we use final variable vitual machine works fast
 
Oleg Tikhonov
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
declaring a variable as final helps enforce the principle of least privilege and such values might not be modified.
I think that virtual machine "works" fast in case when we declaring as final methods or/and classes due to static binding and inlining.

Regards,
Oleg.
 
Piyush Porwal
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Virtual machine (or in fact your application) MAY run fast, it is not the case always. Most of the time it gives performance benefits because as the variable is final, it can be used for compile time optimizations of the code. For example if you are doing
range = MAX_VALUE - MIN_VALUE

where MAX_VALUE and MIN_VALUE are final variables, then this can be calculated at compile time itself and hence gives a minor performance gain. It can scale further, it such things are repeatedly, say in a loop.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a variable is final, the JVM may choose to cache its value in a register instead of retrieving the latest value each time. If a variable is final and either a primitive or a String, then the compiler may substitute its value all over the code (like Piyush) said. Therefore, yes, it may speed up your application. However, the differences are so minute that no human will ever notice it.

Therefore, use final only if required (e.g. for anonymous classes), or if you want to indicate that a value is never allowed to change. Don't do it for performance reasons. (Although the never allowing to change is mostly enough reason, especially with instance fields.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!