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

Posted 土豆丝不辣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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效率优先关系说明的主要内容,如果未能解决你的问题,请参考以下文章

String,StringBuffer与StringBuilder的区别

(转)String,StringBuffer与StringBuilder的区别

重温java中的String,StringBuffer,StringBuilder类

Java常用类--String类(StringBuilder 和 StringBuffer)介绍

StringBuffer和StringBuilder类

StringBuffer的替换功能