Java:String vs StringBuilder vs StringBuffer

来自WHY42

有个题目,String,StringBuilder,StringBuffer三者有什么区别?蛋疼了,这又不是我写的,明显可以看文档的东西,考这个有什么鸟用...

JDK的描述如下:

  • StringBuffer:
    • A thread-safe, mutable sequence of characters.A string buffer is like a {@link String}, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
  • StringBuilder
    • A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible,it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

String类是不可变类,任何对String的改变都 会引发新的String对象的生成;StringBuffer则是可变类,任何对它所指代的字符串的改变都不会产生新的对象。

性能分析

以下是一个测试字符串相加的性能的程序:

public void usingString(int n){
        long t1 = System.currentTimeMillis();
        String str = "";
        for(int i = 0; i < n; i++){
            str += "HelloWorld";
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Using String:" + (t2 - t1));
    }
    
    public void usingStringBuilder(int n){
        long t1 = System.currentTimeMillis();
        StringBuilder str = new StringBuilder();
        for(int i = 0; i < n; i++){
            str.append("HelloWorld");
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Using StringBuilder:" + (t2 - t1)); 
    }
    
    public void usingStringBuffer(int n){
        long t1 = System.currentTimeMillis();
        StringBuffer str = new StringBuffer();
        for(int i = 0; i < n; i++){
            str.append("HelloWorld");
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Using StringBuffer:" + (t2 - t1)); 
    }

执行结果:

--------n=100
Using String:0
Using StringBuilder:0
Using StringBuffer:0

--------n=1000
Using String:8
Using StringBuilder:1
Using StringBuffer:0

--------n=10000
Using String:465
Using StringBuilder:0
Using StringBuffer:1

--------n=100000
Using String:32954
Using StringBuilder:5
Using StringBuffer:4

可见StringBuilder和StringBuffer效率相差不大,在操作次数多时,都远高于String。