Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance advantage to declaring a static value globally over a local variable in Java?

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?

like image 465
TERACytE Avatar asked Mar 21 '23 18:03

TERACytE


1 Answers

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.

like image 122
Philip Voronov Avatar answered Apr 07 '23 13:04

Philip Voronov