Given these code samples:
Sample 1
public class SomeClass {
private static final int onlyUsedByMethodFoo = 1;
// many lines of code
public static void foo() {
final String value = items[onlyUsedByMethodFoo];
}
}
Sample 2
public class SomeClass {
// many lines of code
public static void foo() {
final int onlyUsedByMethodFoo = 1;
final String value = items[onlyUsedByMethodFoo];
}
}
I prefer the second code sample because the value is close to where it is used. It is only used by Foo() anyway. I don't see an advantage declaring it as a global value, even though Foo() is called frequently. The only advantage to a global static value I can see is potentially in performance, but it is unclear how much of a performance advantage it would be. Perhaps Java recognizes this and optimizes the byte-code.
Concerning performance, is it worth declaring a constant value globally? Does the performance gain justify moving a constant value farther from where it is used and read by the programmer?
Java compiler substitutes all occurrences of this static final field by it's value; local variables are part of runtime stack frame. See The Java® Virtual Machine Specification for more comprehensive explanation.
I don't think that in your case there is any difference in performance.
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