by Tony Sintes

Call direct?

news
Jul 20, 20011 min

Should you call a frequently accessed constant directly?

Q:

public class A {
    public final static String NAME = "someone";
    ...
}

You have another class, B, which will use the constant NAME many times. You can use A.NAME directly in B whenever you need it, or you can keep A.NAME as a local variable in B and use the variable.

My question: which approach performs better?

A: This question has a general form: when you need to access a constant or method multiple times, should you call it directly or keep the result of calling it once as a local variable and use the variable whenever you need it?

Referencing the constant as A.NAME works fine. The compiler optimizes accesses to static final fields by resolving these values at compile time. So, if you have the following code:

public class SomeClass {
    public final static int SOME_VALUE = 1;
}

And you access SOME_VALUE in another class such as:

if( SomeClass.SOME_VALUE == var )

The compiler will actually:

if( 1 == var )

So the compiler will give you a local copy. Therefore, there’s no need to make the copy yourself.