activity
activity

Reputation: 2733

java access time to variables

Suppose we have a class Const.java containing 1000 String constants:

public static final String foo1 = "foo1";
public static final String foo2 = "foo2";
...
public static final String foo1000 = "foo1000";

Now, some method in another class executes

String s = Const.foo1000;

Does access time of variables depend on the number of such variables? (That is, if there were 1,000,000 Strings in Const.java, would code run at the same speed?)

Upvotes: 3

Views: 62

Answers (2)

VGR
VGR

Reputation: 44414

Yes, it would run at the same speed. An important reason is that the constants are all resolved at compile time, not at run time.

Any static final field consisting only of literals, or values of other static final fields which consist only of literals, is analyzed when the code is compiled. In fact, if you were to decompile the assigment, you would see:

String s = "foo1000";   // No reference whatsoever to Const

Upvotes: 2

Alex Roig
Alex Roig

Reputation: 1574

The access time will be always the same.

Your class is loaded using the the classloader into RAM memory when the application starts. Constants (static/final) are stored in a memory position that is replaced in your code at compile time wherever it's used.

The only difference that you should notice is at the start time of your application, that will be proportional to the amount of variables that you have in the class.

Accessing a memory position is always O(1), like retrieving an object from a HashMap.

Upvotes: 2

Related Questions