Best practice curiosity regarding String instantiation

13,315

Solution 1

When you use new you get a new string object, but if you use string literal then see here:

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool. The single copy of each string is called its 'intern' and is typically looked up by a method of the string class, for example String.intern() in Java. All compile-time constant strings in Java are automatically interned using this method.

If you do:

String a = "foo";
String b = "foo";

Then a==b is true !

A String will be created only if it hasn't been interned. An object will be created in the first time, and it'll be stored in a place called the String constant pool.

But using the new which will create a different object for each string, will output false.

String a = new String("foo");
String b = new String("foo");

Now a==b is false.

So when using literal it is easier to read, plus easier for the compiler to make optimizations. So.. use it when you can.

Solution 2

The JVM maintains a pool of String literals for optimizations. When you create a String using the constructor,

String s1 = new String("foo");

A new String object is created, and the literal "foo" is added to the pool. After this, anytime you use "foo" in your code, the "foo" refers to the item in the pool and a new object is not created. Since String is immutable, this does not create any problems.

So when you create a String using the "shortcut":

String s2 = "foo"

the JVM looks into the pool, if "foo" already exists there, it will make s2 refer to the item in the pool.

This is a major difference with possible performance impacts: The constructor always creates an object, and adds the literal to the pool if it is not already present there. The shortcut refers to the item in the pool and creates a new object only if the liuteral is not in the pool.

Share:
13,315
Bogdan M.
Author by

Bogdan M.

Learning is the way.

Updated on June 28, 2022

Comments

  • Bogdan M.
    Bogdan M. almost 2 years

    I was reading some advices about best practices in java and I got the following idea which made me curious

    Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly.

    For example:

    //slow instantiation
    String slow = new String("Yet another string object");
    
    //fast instantiation
    String fast = "Yet another string object";
    

    Why is this? doesn't the 'fast' call the default string constructor?