Loading

String,StringBuffer,StringBuilder三者性能对比

编译环境:OpenJDK 11
先上代码:

public class Test {
    public static void main(String[] args) {
        final int n = Integer.parseInt(args[0]);
        System.out.println("String:" + getTime(getStringTime(n)));
        System.out.println("StringBuffer:" + getTime(getStringTime(n)));
        System.out.println("StringBuilder:" + getTime(getStringTime(n)));
    }

    static String getTime(long time) {
        return Double.toString((double) time / 1000);
    }

    static long getStringTime(int times) {
        String string = "";
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            string += ' ';
        }
        long t2 = System.currentTimeMillis();
        return t2 - t1;
    }

    static long getStringBufferTime(int times) {
        StringBuffer stringBuffer = new StringBuffer();
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            stringBuffer.append(' ');
        }
        long t2 = System.currentTimeMillis();
        return t2 - t1;
    }

    static long getStringBuilderTime(int times) {
        StringBuilder stringBuilder = new StringBuilder();
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            stringBuilder.append(' ');
        }
        long t2 = System.currentTimeMillis();
        return t2 - t1;
    }
}

String,StringBuffer,StringBuilder各循环1000000次,两次测试结果分别如下图所示

在自己的电脑上测试的结果(CPU:i7 9700)

i7 9700

在ECS服务器上测试的结果(CPU:云ECS学生机1核CPU)

1c

结论:String,StringBuffer和StringBuilder在现代处理器单线程下性能差异并不大,后两者性能略高于String,而由于String在自增过程中是存在新建对象操作的,所以占用内存方面大于后两者,同时由于产生了垃圾对象,gc也会造成一定的计算开支。因此处理可变长字符串时,在单线程应用场景下应使用StringBuilder获得更高性能,而在多线程应用场景下应使用StringBuffer来确保线程安全。

posted @ 2020-08-04 22:17  Biem  阅读(1062)  评论(0编辑  收藏  举报