/** * 1萬以內沒區別,100萬往上,有區別了 * String 最慢 * StringBuffer 中間級 * StringBuilder 最快 */ @Test public void Test2() { String s1 = "a"; String s2 ="b"; String s3 = "c"; String s4 = null; StringBuilder builder = new StringBuilder(); StringBuffer buffer = new StringBuffer(); //------500萬測試 long t00 = System.currentTimeMillis(); for(int i = 0 ; i< 5000000; i++){ s4 = s1+s2+s3; } long t01 = System.currentTimeMillis(); System.out.println("String:"+(t01-t00)); System.out.println("================="); long t1 = System.currentTimeMillis(); for(int i = 0 ; i< 5000000; i++){ builder.append("a"); } long t2 = System.currentTimeMillis(); System.out.println("StringBuilder :"+ (t2 -t1) ); System.out.println("================="); long t3 = System.currentTimeMillis(); for(int i = 0 ; i<5000000; i++){ buffer.append("b"); } long t4= System.currentTimeMillis(); System.out.println("StringBuffer :"+ (t4 -t3) ); }
//輸出 String:498 ================= StringBuilder :120 ================= StringBuffer :200