StringBuffer和StringBuilder之间的主要区别是什么?在决定其中任何一项时是否存在性能问题?


当前回答

很好的问题

以下是我注意到的差异:

字符串缓冲区:-

StringBuffer is  synchronized
StringBuffer is  thread-safe
StringBuffer is  slow (try to write a sample program and execute it, it will take more time than StringBuilder)

StringBuilder:-

 StringBuilder is not synchronized 
 StringBuilder is not thread-safe
 StringBuilder performance is better than StringBuffer.

常见问题:-

两者都有相同的方法和相同的签名。两者都是可变的。

其他回答

StringBuilder不是线程安全的。字符串缓冲区是。更多信息请点击此处。

编辑:至于性能,在热点启动后,StringBuilder是赢家。然而,对于较小的迭代,性能差异可以忽略不计。

StringBuilder比StringBuffer更快,因为StringBuffer是同步的,StringBuffer有自己的char[]缓冲区用于缓存,就像BufferedInputStream一样。

StringBuffer速度较慢的另一个原因是,每次添加或删除时,它都会更新变量缓冲区。我测试了它,如果我移除超过一万次,StringBuffer的移除方法会更快。

字符串缓冲区是可变的。它可以在长度和内容方面改变。StringBuffers是线程安全的,这意味着它们有同步的方法来控制访问,这样一次只有一个线程可以访问StringBuffer对象的同步代码。因此,StringBuffer对象在多线程环境中使用通常是安全的,因为多个线程可能同时尝试访问同一StringBuffer。

字符串拼接StringBuilder类与StringBuffer非常相似,只是它的访问不同步,因此不是线程安全的。通过不同步,StringBuilder的性能可以优于StringBuffer。因此,如果您在单线程环境中工作,使用StringBuilder而不是StringBuffer可能会提高性能。这也适用于其他情况,例如StringBuilder局部变量(即方法中的变量),其中只有一个线程将访问StringBuilder对象。

StringBuffer已同步,StringBuilder未同步。

很好的问题

以下是我注意到的差异:

字符串缓冲区:-

StringBuffer is  synchronized
StringBuffer is  thread-safe
StringBuffer is  slow (try to write a sample program and execute it, it will take more time than StringBuilder)

StringBuilder:-

 StringBuilder is not synchronized 
 StringBuilder is not thread-safe
 StringBuilder performance is better than StringBuffer.

常见问题:-

两者都有相同的方法和相同的签名。两者都是可变的。