开发者

Why use append() instead of + [duplicate]

This question alread开发者_Go百科y has answers here: Closed 12 years ago.

Possible Duplicate:

Why to use StringBuffer in Java instead of the string concatenation operator

what is the advantage or aim of doing this

int a= 42
StringBuffer sb = new StringBuffer(40); 
String s = sb.append("a = ").append(a).append("!").toString(); 
System.out.println(sb);

result > a = 42!

instead of

 int a= 42
 String s = "a = " + a + "!"; 
 System.out.println(sb);


In your scenario, I'm not sure there is a difference b/c all of your "+" are on one line (which only creates a String once). In general, though, Strings are immutable objects and are not truly manipulated but rather created and discarded using StringBuffers.

So ultimately, you will have more efficient code if you use StringBuffers (and generally StringBuilders). If you google "String vs. StringBuffer vs. StringBuilder" you can find many articles detailing the statistics.


Efficiency. String concatenation in Java uses StringBuilders in the background anyway, so in some cases you can eke out a bit of efficiency by controlling that yourself.


Just run the code for 10000 time and measure the time. It should be obvious. Some background-information: String is immutable while StringBuilder is not. So everytime you concatenate a String you have to copy an array.

PS: Sometimes the compiler optimizes things though. Maybe if you make your variable static final it would be just one String internally and no concatenation.


First of all, StringBuffer is synchronized, so you would typically use StringBuilder. + has been reimplemented to use StringBuilder a while ago.

Second, as @Riggy mentioned Java actually does optimize + as long as they occur in a single expression. But if you were to do:

String s = "";
s += a;
s += b;
s += c;
s += d;

Then the effective code would become:

String s ="";
s = new StringBuilder(s).append(a).toString();
s = new StringBuilder(s).append(b).toString();
s = new StringBuilder(s).append(c).toString();
s = new StringBuilder(s).append(d).toString();

which is suboptimal to String s = new StringBuilder(s).append(a).append(b).append(c).append(d).toString();


Because of compiler optimizations, it may or may not make any difference in your app. You'll have to run comparison speed tests to see.

But before you obsess about performance, get the program working right. "Premature optimization is the root of all evil."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜