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


当前回答

字符串缓冲区

同步,因此线程安全线程安全,因此速度较慢

字符串拼接

在Java 5.0中引入异步,因此快速高效用户明确需要同步它,如果他想您可以将其替换为StringBuffer而无需任何其他更改

其他回答

StringBuilder比StringBuffer更快,因为它不同步。

下面是一个简单的基准测试:

public class Main {
    public static void main(String[] args) {
        int N = 77777777;
        long t;

        {
            StringBuffer sb = new StringBuffer();
            t = System.currentTimeMillis();
            for (int i = N; i --> 0 ;) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }

        {
            StringBuilder sb = new StringBuilder();
            t = System.currentTimeMillis();
            for (int i = N; i > 0 ; i--) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }
    }
}

测试运行得出StringBuffer为2241ms,StringBuilder为753ms。

更好地使用StringBuilder,因为它不是同步的,因此提供了更好的性能。StringBuilder是旧StringBuffer的替代品。

StringBuffer和StringBuilder源之间的差异:

其他人正确地指出了两者之间的关键区别。然而,在性能方面,我想补充一点,JVM级别的优化“锁定Elision”可以使同步上下文中的性能差异几乎不存在。关于这一点的精彩阅读在这里和这里

很好的问题

以下是我注意到的差异:

字符串缓冲区:-

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.

常见问题:-

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