Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...