Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always Use Final?

Tags:

java

loops

final

I have read that making something final and then using it in a loop will bring better performance, but is it good for everything? I have lots of places where there isnt a loop but I add final to the local variables. Does it make it slower or is it still good?

Also there are some places where I have a global variable final (e.g. android paint), does it mean I don't have to make it a local final when using it in loops?

like image 856
nebkat Avatar asked Dec 02 '22 02:12

nebkat


2 Answers

The first thing you should consider is; What is the simplest and clearest way I can write this code. Often this performs well.

final local variables is unlikely to affect performance much. They can help clarity when you have long methods, but I would suggest breaking up method is a better approach.

final fields can affect performance to small degree, but a better reason to make it final is to make it clear that this field never changes (which also helps the JIT)

like image 65
Peter Lawrey Avatar answered Dec 12 '22 04:12

Peter Lawrey


Don't think about performance. final on object member (fields) have significant memory semantics that may improve performance (but more importantly, its often necessary to make the code correctly work at all). You should always put final on object members whenever you can. For local variables however, you should only use it if it will improve code readerability, or can prevent bugs when a maintainer touches your code.

The general consensus of the Java community is that final on every local variables will make the code difficult to read. On the performance front, you can expect no optimization as local variables are easy to analyze for the compiler. In other words, the compiler can figure it out by itself.

like image 21
Enno Shioji Avatar answered Dec 12 '22 05:12

Enno Shioji