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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With