我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?
我正在工作的程序有很多case驱动的字符串追加(500+)。使用StringBuilder是更好的选择吗?
我理解String和StringBuilder之间的区别(StringBuilder是可变的),但两者之间有很大的性能差异吗?
我正在工作的程序有很多case驱动的字符串追加(500+)。使用StringBuilder是更好的选择吗?
当前回答
我相信StringBuilder更快,如果你有超过4个字符串,你需要附加在一起。此外,它可以做一些很酷的事情,如AppendLine。
其他回答
使用字符串进行连接会导致运行时复杂度达到O(n^2)的量级。
如果使用StringBuilder,需要复制的内存就会少得多。使用StringBuilder(int capacity),如果您可以估计最终字符串的大小,则可以提高性能。即使不精确,也可能只需要将StringBuilder的容量增加几倍,这也有助于提高性能。
我相信StringBuilder更快,如果你有超过4个字符串,你需要附加在一起。此外,它可以做一些很酷的事情,如AppendLine。
从内存的角度来看,StringBuilder的性能会更好。至于处理,执行时间的差异可以忽略不计。
The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.
来源:MSDN
字符串连接将花费更多。 在Java中,您可以根据需要使用StringBuffer或StringBuilder。 如果您想要一个同步的、线程安全的实现,请使用StringBuffer。这将比字符串连接更快。
如果你不需要同步的或者线程安全的实现,选择StringBuilder。 这将比String连接更快,也比StringBuffer更快,因为它们没有同步开销。