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

Given these code examples:

Example 1

public class SomeClass {
    private static final int onlyUsedByMethodFoo = 1;
    // many lines of code
    public static void foo() {
        final String value = items[onlyUsedByMethodFoo];
    }
}

Example 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 used only by foo (). I see no benefit declaring this a global value, although Foo () is often called. The only advantage to the global static value that I can see can potentially be related to performance, but it is unclear how much this is beneficial to performance. Perhaps Java recognizes this and optimizes the byte code.

, ? , , ?

+4
5

Java- ; . . Java®.

, - .

+5

-, - - , . , , .

- , .

, , , - , - -.

:

  • , .
  • , , .

, , , public. - , Sample 1, private static final int onlyUsedByMethodFoo = 1;.

+2

( ) . , " ", , . , , , , , .

0

. , . , ( ) . - . , .

0

JIT / Java , , . , , static final , final.

, (an int), ; , . , , - ; final int:

void foo() {
final Object o = new SomeObject();
}

, final , , o , , .. == o . , .

It’s not clear to me whether JIT needs to optimize or not optimize primitives finalin methods, because it could only optimize it if it is stored in one place, but it is clear that for reference types, the class member will be (slightly) lower invoice in terms of memory / CPU.

0
source

Source: https://habr.com/ru/post/1524357/


All Articles