Using static variables for Strings
- by Vivart
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.