Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About string concatenation behaviours

I understand that, given the immutability of strings, something like

String a="";
for(int i=0;i++<9;)
    a+=i;

is highly inefficient, because initially a string is instantiated and put in the string pool, then with a+=i a new string is created (0 in the first loop), referenced by a and the previous one is now eligible for garbage collection. And this happens nine times.

A better way is using StringBuilder:

StringBuilder a=new StringBuilder("");
for(int i=0;i++<9;)
    a.append(i);

But what happens behind the scenes when I instantiate the string with the new keyword?

String a=new String("");
for(int i=0;i++<9;)
    a+=i;

I know that in this case a doesn't get interned (it's not in the string pool), but is it still immutable? What does the a+=i instruction do in this time? Is the behaviour identical to my first example?

like image 568
Luigi Cortese Avatar asked Mar 15 '23 20:03

Luigi Cortese


1 Answers

Only String literals, or Strings you call the intern() method on are put in the String pool. Concatenation does not automagically intern a String, so your examples will be identical with regards to the String pool.

String abc = new String("abc"); //"abc" is put on the pool
abc += "def"; //"def" is put on the pool, but "abcdef" is not
String xyz = "abcdefghi".substring(0, 6).intern(); //"abcdef" is now added to the pool and returned by the intern() function
String xyz = "test"; //test is put on the pool
xyz += "ing"; //ing is put on the pool, but "testing" is not

And to expand on this, note that the String constructor does not intern (or not intern) a String automatically. The use of String literals (Strings in quotation marks in your code) is what causes the String to be on the String pool.

String abc = "abc"; //"abc" is in the pool
String def = "def"; //"def" is in the pool
String str1 = new String(abc + def); //"abcdef" is not in the pool yet
String str2 = new String("abcdef"); //"abcdef" is on the pool now

Also note that the String copy constructor is almost never used, since Strings are immutable anyway.

For more info, read the answers here, here, and here.

like image 107
Kevin Workman Avatar answered Mar 18 '23 13:03

Kevin Workman