Java access time to variables

Let's say we have a class Const.java

that contains 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 does

String s = Const.foo1000;

      

Does the access time of variables depend on the number of such variables? (That is, if Const.java

there were 1,000,000 lines in, would the code run at the same speed?)

+3


source to share


2 answers


The access times will always be the same.

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



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

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

+2


source


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

Analyzed any static final field consisting only of literals or the values ​​of other static final fields consisting only of literals when compiling the code. In fact, if you want to decompile the assistant, you will see:



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

      

+2


source







All Articles