Java如何使用“+”进行字符串连接? [英] How Java do the string concatenation using "+"?
问题描述
我使用 StringBuilder
阅读了Java与 + =
运算符一起工作的方式。
与(a+b)
操作相同吗?
I read about the way Java works with +=
operator, using StringBuilder
.
Is it the same with a ("a" + "b")
operation?
推荐答案
不。使用
StringBuilder
与执行a+b
不一样。
在Java中,String实例是不可变的。
In Java, String instances are immutable.
所以,如果你这样做:
String c = "a" + "b";
每次连接时都会创建新的字符串。
You are creating new Strings every time you concatenate.
另一方面,StringBuilder就像一个缓冲区,可以在追加新字符串时增长。
On the other hand, StringBuilder is like a buffer that can grow as it needs when appending new Strings.
StringBuilder c = new StringBuilder();
c.append("a");
c.append("b"); // c is only created once and appended "a" and "b".
拇指规则(由于我收到的评论而改变):
Rule of the thumb is (changed thanks to the comments I got):
如果要连接很多(例如,在循环内连接,或生成由多个字符串连接变量组成的大型XML),请使用StringBuilder。否则,简单的连接(使用+运算符)就可以了。
If you are going to concatenate a lot (i.e., concatenate inside a loop, or generating a big XML formed by several string concatenated variables), do use StringBuilder. Otherwise, simple concatenation (using + operator) will be just fine.
编译这种代码时,编译器优化也起到了重要作用。
Compiler optimizations also play a huge role when compiling this kind of code.
这里有关该主题的进一步说明。
Here'sfurther explanation on the topic.
关于此问题的更多StackOVerflow问题:
And more StackOVerflow questions on the issue:
StringBuilder vs Java中toString()的字符串连接
这篇关于Java如何使用“+”进行字符串连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!