字符串是不可变的 - 这意味着我永远不应该使用+ =而且只能使用StringBuffer? [英] Strings are immutable - that means I should never use += and only StringBuffer?
问题描述
字符串是不可变的,这意味着,一旦创建它们就无法更改。
Strings are immutable, meaning, once they have been created they cannot be changed.
所以,这是否意味着如果你追加东西需要更多内存+ =如果你创建了一个StringBuffer并附加了文本?
So, does this mean that it would take more memory if you append things with += than if you created a StringBuffer and appended text to that?
如果使用+ =,每次必须保存时都会创建一个新的'对象'在记忆中,不是吗?
If you use +=, you would create a new 'object' each time that has to be saved in the memory, wouldn't you?
推荐答案
是的,每次用+ =创建一个新对象。但这并不意味着它总是错误的做法。这取决于你是否希望将该值作为字符串,或者是否只是用它来进一步构建字符串。
Yes, you will create a new object each time with +=. That doesn't mean it's always the wrong thing to do, however. It depends whether you want that value as a string, or whether you're just going to use it to build the string up further.
如果你实际上想要 x + y
的结果作为字符串,那么你也可以使用字符串连接。但是,如果你真的要(比方说)循环并附加另一个字符串,另一个字符串等 - 只需要将结果作为字符串放在最后,那么StringBuffer / StringBuilder就是你要走的路。实际上,循环实际上是StringBuilder在字符串连接中得到的回报 - 5个甚至10个直接连接的性能差异将非常小,但是对于数千个,它变得更糟 - 基本上因为你得到O(N 2 )串联与StringBuilder的O(N)复杂性的复杂性。
If you actually want the result of x + y
as a string, then you might as well just use string concatenation. However, if you're really going to (say) loop round and append another string, and another, etc - only needing the result as a string at the very end, then StringBuffer/StringBuilder are the way to go. Indeed, looping is really where StringBuilder pays off over string concatenation - the performance difference for 5 or even 10 direct concatenations is going to be quite small, but for thousands it becomes a lot worse - basically because you get O(N2) complexity with concatenation vs O(N) complexity with StringBuilder.
在Java 5及以上版本中,你基本上应该使用StringBuilder - 它是不同步的,但这几乎是总是好的;想要在线程之间共享一个是非常罕见的。
In Java 5 and above, you should basically use StringBuilder - it's unsynchronized, but that's almost always okay; it's very rare to want to share one between threads.
我有一个关于所有这些的文章你可能会觉得有用。
I have an article on all of this which you might find useful.
这篇关于字符串是不可变的 - 这意味着我永远不应该使用+ =而且只能使用StringBuffer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!