📜  Java stringbuffer和stringbuilder之间的差异

📅  最后修改于: 2020-09-25 14:58:42             🧑  作者: Mango

StringBuffer和StringBuilder之间的区别

Java提供了三个类来表示字符序列:String,StringBuffer和StringBuilder。String类是不可变的类,而StringBuffer和StringBuilder类是可变的。StringBuffer和StringBuilder之间有很多区别。从JDK1.5开始引入StringBuilder类。

下面列出了StringBuffer和StringBuilder之间的差异:

No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can’t call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

StringBuffer示例

//Java Program to demonstrate the use of StringBuffer class.  
public class BufferTest{  
    public static void main(String[] args){  
        StringBuffer buffer=new StringBuffer("hello");  
        buffer.append("java");  
        System.out.println(buffer);  
    }  
}  

StringBuilder示例

//Java Program to demonstrate the use of StringBuilder class.  
public class BuilderTest{  
    public static void main(String[] args){  
        StringBuilder builder=new StringBuilder("hello");  
        builder.append("java");  
        System.out.println(builder);  
    }  
}  

StringBuffer和StringBuilder的性能测试

让我们看一下检查StringBuffer和StringBuilder类性能的代码。

//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.  
public class ConcatTest{  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
        StringBuilder sb2 = new StringBuilder("Java");  
        for (int i=0; i<10000; i++){  
            sb2.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}