測試StringBuilder、StringBuffer、String類之間的關係



來至:gotesting軟件測試聯盟論壇   http://www.78test.com


 public class TestCharacter {

 final static int time = 50000;  //循環次數
 
 public TestCharacter(){
  
 } 
 public void test(String s){
  long begin = System.currentTimeMillis();
  for(int i=0; i<time; i++){
   s += "add";
  }
  long over = System.currentTimeMillis();
  System.out.println("操作"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
 }
 public void test(StringBuffer s){
  long begin = System.currentTimeMillis();
  for(int i=0; i<time; i++){
   s.append("add");
  }
  long over = System.currentTimeMillis();
  System.out.println("操作"+s.getClass().getCanonicalName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
 }
 public void test(StringBuilder s){
 long begin = System.currentTimeMillis();
 for(int i=0; i<time; i++){
  s.append("add");
 }
 long over = System.currentTimeMillis();
 System.out.println("操作"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
 }

/*對 String 直接進行字符串拼接的測試*/ 
 public void test2(){
  String s2 = "abcd";
  long begin = System.currentTimeMillis();
  for(int i=0; i<time; i++){
   String s = s2 + s2 +s2;
  }
  long over = System.currentTimeMillis();
  System.out.println("操作字符串對象引用相加類型使用的時間爲:"+(over-begin)+"毫秒");
 }
 public void test3(){
  long begin = System.currentTimeMillis();
  for(int i=0; i<time; i++){
   String s ="abcd" + "abcd" + "abcd";
  }
  long over = System.currentTimeMillis();
  System.out.println("操作字符串相加使用的時間爲:"+(over-begin)+"毫秒");
 }
 public static void main(String[] args){
  String s1 = "abcd";
  StringBuffer st1 = new StringBuffer("abcd");
  StringBuilder st2 = new StringBuilder("abcd");
  TestCharacter tc = new TestCharacter();
  tc.test(s1);
  tc.test(st1);
  tc.test(st2);
  tc.test2();
  tc.test3();
 }
}
我在myeclipse和dos下都運行了這段代碼,各自打印出的時間有些不同,運行結果如下:
1)myeclipse下循環10000次時:

2)myeclipse下循環50000次時:

3)在DOS下運行時:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章