Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static variables for Strings

below content is taken from Best practice: Writing efficient code but i didn't understand why

private static String x = "example";

faster than

private static final String x ="example";

Can anybody explain this.

Using static variables for Strings

When you define static fields (also called class fields) of type String, you can increase application speed by using static variables (not final) instead of constants (final). The opposite is true for primitive data types, such as int.

For example, you might create a String object as follows:

private static final String x = "example";

For this static constant (denoted by the final keyword), each time that you use the constant, a temporary String instance is created. The compiler eliminates "x" and replaces it with the string "example" in the bytecode, so that the BlackBerry® Java® Virtual Machine performs a hash table lookup each time that you reference "x".

In contrast, for a static variable (no final keyword), the String is created once. The BlackBerry JVM performs the hash table lookup only when it initializes "x", so access is faster.

private static String x = "example";

You can use public constants (that is, final fields), but you must mark variables as private.

like image 784
Vivart Avatar asked May 10 '10 10:05

Vivart


2 Answers

I wasn't aware of this, but it makes sense to me:

The JVM has an internal String Literal Cache. Everytime you create a String by using a literal, the JVM has to look for it in the cache and if it isn't there, store it.

Now a compiler can inline a final variable with a String literal, because it is known at compile time and it seems to be a good idea for performance.

So your code:

static final String CONST = "myconst";
...
if (CONST.equals(aVar))
...
case CONST
...

is rewritten by the compiler to:

static final String CONST = "myconst";
...
if ("myconst".equals(aVar))
...
case "myconst"
...

If the JVM implementation isn't clever enough, it needs to look up "myconst" three times in this example.

When you don't mark CONST as "final", the compiler can't "optimize" it since the variable can change at runtime. Your code would be compiled 1:1 and the JVM only needs to look for the Object at the variable.

btw: Bad JVM implementations shouldn't define your coding style. "final" gives a lot of safety, so as long as it doesn't really hit your performance: Don't care about if it increase or decrease you speed - its different for the next JVM anyhow

like image 168
Hardcoded Avatar answered Oct 23 '22 03:10

Hardcoded


the text explains it, just read it.

but to reword it: Its faster because it is. The way blackberry jvm is made its better to use the non final version. Its like that because its designed in that fashion

like image 25
Peter Avatar answered Oct 23 '22 02:10

Peter