Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will things run quicker if I make my variables final?

Tags:

java

android

I'm writing for Android (Java).

I'm declaring int's and float's as part of an ongoing loop.

Some of them don't need to be changed after declaration.

If I set them all to final when declaring, will things run quicker?

[Edit]

Thanks everyone. I didn't actually expect it to make any improvements, I just noticed, after browsing the source of various large projects, it was fairly common. Cheers

like image 347
Richard Taylor Avatar asked Jun 25 '10 11:06

Richard Taylor


People also ask

Are final variables faster?

In general, final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded at compile-time, See these Java Performance courses for more details.

Does adding final improve performance?

Classes and MethodsThere are no reported performance benefits of applying final to classes and methods. Moreover, final classes and methods can be a cause of great inconvenience for developers, as they limit our options for reusing existing code.

Should I make variables final?

Method parameters and local variables should not be declared final unless it improves readability or documents an actual design decision. Fields should be declared final unless there is a compelling reason to make them mutable.

What happens when you make a variable final?

The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program.


1 Answers

Things will not run quicker. The final keyword is just compile time syntactic sugar.


If it were actually static final, then you could take benefit of compiletime calculation and inlining of the value in any refernce. So, with for example:

private static final long ONE_WEEK_IN_MILLIS = 7 * 24 * 60 * 60 * 1000L;

public void foo(Date date) {
    if (date.getTiem() > System.currentTimeMillis() + ONE_WEEK_IN_MILLIS) {
        // No idea what to do here?
    }
}

the compiler will optimize one and other so that it ends up like:

private static final long ONE_WEEK_IN_MILLIS = 604800000L;

public void foo(Date date) {
    if (date.getTiem() > System.currentTimeMillis() + 604800000L) {
        // No idea what to do here?
    }
}

If you run a decompiler, you'll see it yourself.

like image 78
BalusC Avatar answered Sep 19 '22 17:09

BalusC