JAVA中字符串操作几种方式对比

@参考文章

方法及原理:

方法1:a=a+b实际上另开辟一个空间c=a+b;然后将c的引用赋给a

方法2:a += b实际上是建立一个StringBuffer,然后调用append(),最后再将StringBuffer toSting();等同于StringBuffer sb=new StringBuffer(a);sb.ppend(b);a=sb.toString();

方法3:a.append(b);StringBuffer.append(字符串)

方法4:a.append("1" + "2");StringBuffer.append(字符串相加)

方法5:a.append("1");a.append("2");多次StringBuffer.append()

完整代码如下:注意方法3、4、5比方法1、2运算多了一个数量级

public class Test {
    public static void main(String[] args) throws Exception {
        //为了避免垃圾回收影响,分多次执行。
        for (int k = 0; k < 3; k++) {
            // method1();
             //method2();
            // method3();
            // method4();
             method5();
        }
    }

    // 方法1,定义两个字符串相加
    private static void method1() {
        long start = System.currentTimeMillis();
        String a = new String();
        for (int i = 0; i < 100000; i++) {
            String b = "1";
            a = a + b;
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    // 方法2,定义一个字符串然后+=
    private static void method2() {
        long start = System.currentTimeMillis();
        String a = new String();
        for (int i = 0; i < 100000; i++) {
            String b = "1";
            a += b;
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    // 方法3,StringBuffer 多个append
    private static void method3() {
        long start = System.currentTimeMillis();
        StringBuffer a = new StringBuffer();
        for (int i = 0; i < 1000000; i++) {
            a.append("1");
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    // 方法4,StringBuffer 多个append
    private static void method4() {
        long start = System.currentTimeMillis();
        StringBuffer a = new StringBuffer();
        for (int i = 0; i < 1000000; i++) {
            a.append("1" + "2");
        }
        System.out.println(System.currentTimeMillis() - start);
    }

    // 方法5,StringBuffer 多个append
    private static void method5() {
        long start = System.currentTimeMillis();
        StringBuffer a = new StringBuffer();
        for (int i = 0; i < 1000000; i++) {
            a.append("1");
            a.append("2");
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}
View Code

各自运算结果如下:

方法1:2827、2926、2965

方法2:2771、2994、3072

方法3:33、27、26

方法4:38、29、28

方法5:58、53、54

结论:大数据量操作字符串时,性能上

1、StringBuffer明显优于String

2、StringBuffer.append(字符串相加)优于多次StringBuffer.append()

原文地址:https://www.cnblogs.com/yanan7890/p/10488650.html