问题描述
我很好奇两者之间有什么区别。
I'm curious what is the difference between the two.
我理解字符串池的方式如下:
The way I understand the string pool is this:
这会在字符串池中创建3个字符串对象,其中2个字符串对象丢失。
This creates 3 string objects in the string pool, for 2 of those all references are lost.
String mystr = "str";
mystr += "end";
这不会在字符串池中创建3个对象吗?
Doesn't this also create 3 objects in the string pool?
String mystr = "str";
mystr = mystr.concat("end")
我知道StringBuilder和StringBuffer很多当存在大量的连接时,在内存使用方面更有效。我只是好奇,如果在内存使用方面+运算符和concat之间有任何区别。
I know StringBuilder and StringBuffer are much more efficient in terms of memory usage when there's lots of concatination to be done. I'm just curious if there's any difference between the + operator and concat in terms of memory usage.
推荐答案
没有区别这个特例; 但是,它们通常不一样。
There's no difference in this particular case; however, they're not the same in general.
str1 + = str2
相当于执行以下操作:
str1 += str2
is equivalent to doing the following:
str1 = new StringBuilder().append(str1).append(str2).toString();
为了向自己证明这一点,只需制作一个带两个字符串且 + = 是第二个字符串,然后检查反汇编的字节码。
To prove this to yourself, just make a simple method that takes two strings and +=
's the first string to the second, then examine the disassembled bytecode.
相比之下, str1 .concat(str2)
只需创建一个新字符串,它是 str1
和 str2
的串联,对于少量串联字符串来说成本较低(但是对于第一种方法会丢失较大的数字)。
By contrast, str1.concat(str2)
simply makes a new string that's the concatenation of str1
and str2
, which is less expensive for a small number of concatenated strings (but will lose to the first approach with a larger number).
此外,如果 str1
为空,请注意 str1.concat(str2)
抛出一个NPE,但 str1 + = str2
只会将 str1
视为无效,而不会抛出异常。 (也就是说,它产生null与 str2
的值连接。如果 str2
是,那么,foo ,你最终会得到nullfoo。)
Additionally, if str1
is null, notice that str1.concat(str2)
throws a NPE, but str1 += str2
will simply treat str1
as if it were null without throwing an exception. (That is, it yields "null" concatenated with the value of str2
. If str2
were, say, "foo", you would wind up with "nullfoo".)
更新:参见 ,几乎相同。
Update: See this StackOverflow question, which is almost identical.
这篇关于String concat和Java中的+运算符有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!