JAVA中字符串操作幾種方式對比
阿新 • • 發佈:2019-03-07
sed str aps exceptio clas src sys sta 完整
@參考文章
方法及原理:
方法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(); } }View Code// 方法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); } }
各自運算結果如下:
方法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()
JAVA中字符串操作幾種方式對比