I noticed a comment made in this support forums thread about the use of StringBuffer on BlackBerry which stated that static final String variables should be avoided, and static non-final Strings should be used instead.

There is a statement in the Writing Efficient J2ME Software guide that says:

When defining static fields (also called class fields) of type String, you can increase program 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:

private static final String x = "example";

For this static constant (denoted by the final keyword), a temporary String instance is created every time you use the constant. The compiler eliminates x and replaces it with the string "example" in the bytecode, so that the virtual machine (VM) has to perform a hash table lookup each time you reference x. In contrast, for a static variable (no final keyword), the String is created once. The VM performs the hash table lookup only when it initializes x, which makes access faster.

One thing to note is that although non-final Strings are faster, final Strings will consume less memory. Each referenced static non-final String will stay around in memory, whereas final Strings are essentially duplicated at compile time and are only temporary. Over time final Strings would use less memory, however if used excessively they could build up a large number of object handles at once.

Deciding which to use depends on the nature of your project.
non-final: faster speed
final: cheaper on memory

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

© 2011 Metova, Inc.