Java字符串连接效率

Mar*_*k W 20 java string coding-style concatenation

这不好吗?

(想象它更大)

int count;
//done something to count
String myString = "this " + "is " + "my " + "string" + "and " + this.methodCall() + " answer " + "is : " + count;
Run Code Online (Sandbox Code Playgroud)

或者在StringBuilder/StringBuffer中更好?

小智 32

Java编译器会将其转换为StringBuilder以提高重复字符串连接的性能.http://java.sun.com/docs/books/jls/third%5Fedition/html/expressions.html#15.18.1.2

当你在循环中连接时,编译器不能单独替换StringBuilder,而是应该从串联到StringBuilder.


Kla*_*äck 5

不,还好。如果使用Sun的Java 6编译器,它将实际上使用StringBuilder。

阅读这篇文章


Pet*_*rey 5

来自 Java 5.0 的 StringBuffer 状态的 Javadoc

通常应该优先使用 StringBuilder 类,因为它支持所有相同的操作,但速度更快,因为它不执行同步。

编译器将组合字符串文字,因此它与写作相同

String myString = "this is my stringand " + this.methodCall() + " answer is : " + count;
Run Code Online (Sandbox Code Playgroud)

这与

String myString = new StringBuilder().append("this is my stringand ").append(methodCall()).append(" answer is : ").append(count).toString();
Run Code Online (Sandbox Code Playgroud)

除非您需要从系统中消除垃圾,否则我不会担心性能,在这种情况下,您不会在这里使用字符串。(您不太可能需要担心)