Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...