Java:String vs StringBuilder vs StringBuffer

来自WHY42
imported>Soleverlee2016年4月14日 (四) 11:29的版本

有个题目,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.

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

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)); 
    }