javastringperformancecoding-style

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


Solution

  • 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).