Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet again on string append vs concat vs +

May be I am splitting hair, but I was wondering in the following case:

String newString = a + b + c;  //case 1   String newString = a.concat(b).concat(c);   //case 2  StringBuilder newString = new StringBuilder(); //case 3 newString.append(a); newString.append(b);     newString.append(c); 

Which is the best to use?

Best I mean in any way.

Reading about these, other posts say that the case 3 is not that optimal performance wise, others that case 1 will end up in case 3 etc.

To be more specific.

E.g., setting all aside, which style is more suitable to see it from another programmer if you had to maintain his code?

Or which would you consider as more programming efficient?
Or you would think is faster etc.

I don't know how else to express this.

An answer like e.g. case 3 can be faster but the vast majority of programmers prefer case 1 because it is most readable is also accepted if it is somehow well elaborated

like image 748
Cratylus Avatar asked Jan 22 '12 16:01

Cratylus


People also ask

What is the difference between append and concat?

"Concatenate" joins two specific items together, whereas "append" adds what you specify to whatever may already be there.

What is difference between concat () and operator in string?

+ operator could take any type of input and convert it to a string before append to the target string. The concat method would create new string object as output after appending only if output string has length greater than zero otherwise return the same target string as an output object.

What's the difference between '+' operator and concat () method?

concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.


1 Answers

Case 1 is concise, expresses the intent clearly, and is equivalent to case 3.

Case 2 is less efficient, and also less readable.

Case 3 is nearly as efficient as case 1, but longer, and less readable.

Using case 3 is only better to use when you have to concatenate in a loop. Otherwise, the compiler compiles case 1 to case 3 (except it constructs the StringBuilder with new StringBuilder(a)), which makes it even more efficient than your case 3).

like image 78
JB Nizet Avatar answered Oct 01 '22 01:10

JB Nizet