Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String builder vs string concatenation [duplicate]

What is the benefit and trade-off of using a string builder over pure string concatenation?

new StringBuilder(32).append(str1)                      .append(" test: ")                      .append(val)                      .append(" is changed")                      .toString(); 

vs say

str1 + " test: " + val + " is changed". 

str1 is a random 10 character string. str2 is a random 8 character string.

like image 728
Chun ping Wang Avatar asked Aug 26 '13 21:08

Chun ping Wang


People also ask

Is StringBuilder better than concatenation?

It is always better to use StringBuilder. append to concatenate two string values.

Which is faster string concatenation or the StringBuilder class?

Note that regular string concatenations are faster than using the StringBuilder but only when you're using a few of them at a time. If you are using two or three string concatenations, use a string.

Why StringBuilder is faster than string concatenation?

StringBuilder is faster because StringBuilder is a mutable class while Sting is an immutable class. In StringBuilder we can use the + operator mean you can append by the same object so it is much faster. In the String class if you append then it should be created a new object.

Are StringBuilder and string identical types?

StringBuilder and String are completely different objects.


1 Answers

In your particular example, none because the compiler internally uses StringBuilders to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create several StringBuilder and String objects. For example:

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

Each time line 3 above is executed, a new StringBuilder object is created, the contents of s appended, "a" appended, and then the StringBuilder is converted into a String to be assigned back to s. A total of 10 StringBuilders and 10 Strings.

Conversely, in

StringBuilder sb= new StringBuilder() ; for(int i= 0 ; i < 10 ; i++ )     sb.append( "a" ); String s= sb.toString() ; 

Only 1 StringBuilder and 1 String are created.

The main reason for this is that the compiler could not be smart enough to understand that the first loop is equivalent to the second and generate more efficient (byte) code. In more complex cases, it's impossible even for the smartest compiler to know. If you absolutely need this optimization, you have to introduce it manually by using StringBuilders explicitly.

like image 65
Mario Rossi Avatar answered Sep 23 '22 08:09

Mario Rossi