Performance in creating strings in Java

Asked

Viewed 378 times

21

What is the best way to create strings in Java to get better performance? Here are two examples of creating strings in Java:

Ex. 1:

String str = "string";

Ex. 2:

String str = new String("string");
  • I’m no Java authority to talk about it, but I believe that in the current version of the Framework, both forms may be equivalent (assuming there is internalization).

2 answers

17

In the first case it is always the same object being recovered from String Constant Pool in the latter case, a new object is being created.

String str = new String("foo");

You force the creation of a new object String and it consumes a little time and memory.

String str = "foo";

str will only be created for the first time (a new object), and will be cached in String Constant pool, so every time you refer to it in its literal form, you’re getting exactly the same object, which is quite fast.

String str = "foo";

To JVM performs some tricks while instantiating literal strings/objects to increase performance and decrease memory overload. To reduce the number of objects String servants, A JVM maintains a special memory called String Constant pool. Each time you create a literal string, the JVM checks the String Constant pool first.

If the string already exists in String Pool, a reference to the instance is returned. If the string does not exist, a new object String is created and placed in the Pool. A JVM maintains at most one object of any String in the Pool. Strings literals always refer to an object in String Pool.

How It Works?

The JVM checks the String Constant Pool first, and if the string does not exist, a new String object is created foo and a reference is maintained in the Pool. The variable str also refers to the same object.

And if we have a statement like that?

String str2 = "foo";

To JVM checks the String Constant Pool and once the string already exists, a reference to the instance is returned to str2. This declaration does not create any object String in memory and str2 refers to the same object as str.

To verify this, you can compare two references String using the operator ==(see also How to compare Strings in Java?) to verify whether two references refer to the same object String in memory.

String str = new String("foo");
String str2 = new String("foo");
String str3 = "foo";
String str4 = "foo";

System.out.println(str == str2);   // false
System.out.println(str == str3);   // false
System.out.println(str3 == str4);  // true

Ideone

str3 and str4 are the same object so the comparison == is true.

Illustration:

inserir a descrição da imagem aqui

References

  1. new String() vs literal string performance
  2. String Literal Pool
  • 2

    Just adding: if you need to create new instances of String, for example, to represent textually numeric user entries (String.valueOf(qtdInformada)), you can save memory by storing the reference returned by the method ".intern()" String you just created. This will cause your string to be added or retrieved from Pool. Remember to assign the return of the method to the variable that stored its created string, otherwise it will be two objects in memory instead of one!

15


The reply from @Qmechanic73 is good, however it raised a question that I just researched to understand. Why in the example a==c and b==c always return false?

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

System.out.println(a == c); // False
System.out.println(b == c); // False

To complement his response, when you create a String with the operator new you’re creating an object for this String in the heap and when it creates the String without the new you are seeking a String in pool de Strings, meanwhile if you don’t have any String in pool a new String is created, whether or not a String identical in the heap.

So only in comparison of the two Strings created without the operator new returns true.

An example taken from of this site here.

In doing so:

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // mesma referência
String s4 = new String("Hello");  // objeto String 
String s5 = new String("Hello");  // objeto String

If you have it:

inserir a descrição da imagem aqui

Notice that in case the s4 and the s5 were created before the s1, s2 and s3 the diagram would not be altered, it would be the same as the above.

Answering your question, the best way to create Strings is without the operator new, as the chances of reusing String are bigger, since every time you need a String and it already exists will not be necessary to create another.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.