5

I am developing an Android app with Android Studio, and I ran a code analysis. In many different pieces of code, the analysis suggests that some variables' "Declaration can have final modifier".

Indeed all those variables are set only once and it's done in the constructor, and as of today, there would be no problems if I did declare them as final.

I was wondering if by doing so, there would be any performance improvements, if the code would run more efficiently. In other words, why is the IDE suggesting me this change?

Secondly, is it good practice to declare variables final whenever possible? Are there cases where it could be declared as such, but I'd better not?

Guilherme
  • 7,839
  • 9
  • 56
  • 99
  • 2
    It is not going to improve performance but... It will stop you from doing things you dont want to This wiki is helpful http://en.wikipedia.org/wiki/Final_%28Java%29 – buzzsawddog Apr 16 '14 at 17:56
  • 1
    No improvement in performance http://stackoverflow.com/a/7067312/2182351 – Mani Apr 16 '14 at 17:58
  • 2
    The code *might* be infinitesimally faster (it depends on constant folding). Making your variables [immutable](http://en.wikipedia.org/wiki/Immutable_object) has a [few advantages](http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html). – Elliott Frisch Apr 16 '14 at 17:59
  • There are different reasons why they included the keyword `final` in the language. And, IMHO, efficiency isn't one of those reasons. If your application is not efficient enough then the reason would be something else. I think overuse of the final will only make your code awkward. – Bhesh Gurung Apr 16 '14 at 18:07
  • Thanks for the references. So it basically has no performance influence, and no special reason to change them. Like, "Hey, if you're not gonna change these values, just mark them as `final` so you know they won't change."? – Guilherme Apr 16 '14 at 18:08

0 Answers0