Wednesday, August 30, 2006

Try not Create Extra String Objects

When a Java compiler encounters a string literal, it scans all the strings in its current cache for another String object with the same literal value and, if it exists, reuses the object. If the string does not already exist, the compiler creates a new String object to hold the literal value and places it in a pool.

String myFirst = "A literal";
String mySecond = "A literal";

Here myFirst and mySecond are two different references to one String object.

If you use the new keyword each time you create a string, a new string object will be created every time, even if you use the same literal value.

String myFirst = new String("A literal");
String mySecond = new String("A literal");

Here myFirst and mySecond are references to two different objects.

So creating strings without using the new keyword can prevent you from needlessly creating extra String objects.

No comments: