首页 > 代码库 > String,StringBuffer,StringBuilder效率优先关系说明

String,StringBuffer,StringBuilder效率优先关系说明

String,StringBuffer,StringBuilder效率优先关系说明:

public class StringBufferWithStringBuilder {

    public static void testString() {
        long start = System.currentTimeMillis();
        String str = null;
        for (int i = 0; i < 50000; i++) {
            str = str + i + ",";
        }
        System.out.println("String耗时:"+(System.currentTimeMillis() - start));
    }

    public static void testStringBuffer() {
        long start = System.currentTimeMillis();

        StringBuffer sbuf = new StringBuffer();
        for (int i = 0; i < 50000; i++) {
            sbuf.append(i + ",");
        }
        System.out.println("StringBuffer耗时:"+(System.currentTimeMillis() - start));
    }

    public static void testStringBulider() {
        long start = System.currentTimeMillis();

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 50000; i++) {
            builder.append(i + ",");
        }
        System.out.println("StringBuilder耗时:"+(System.currentTimeMillis() - start));
    }

    public static void main(String[] args) {
        testString();
        testStringBuffer();
        testStringBulider();
    }

}

  

  控制台输出结果:

String耗时:8253
StringBuffer耗时:9
StringBuilder耗时:8

Process finished with exit code 0

结论:可想而知,效率最高的是StringBuilder>StringBuffer>String

String,StringBuffer,StringBuilder效率优先关系说明