首頁  >  文章  >  Java  >  Java 實例 - 字串最佳化

Java 實例 - 字串最佳化

黄舟
黄舟原創
2017-02-22 09:49:111335瀏覽

以下實例示範了透過String.intern() 方法來最佳化字串:

//StringOptimization.java 文件public class StringOptimization{
   public static void main(String[] args){
      String variables[] = new String[50000];	  
      for( int i=0;i <50000;i++){
         variables[i] = "s"+i;
      }
      long startTime0 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         variables[i] = "hello";
      }
      long endTime0 = System.currentTimeMillis();
      System.out.println("Creation time" 
      + " of String literals : "+ (endTime0 - startTime0) 
      + " ms" );
      long startTime1 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         variables[i] = new String("hello");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Creation time of" 
      + " String objects with &#39;new&#39; key word : " 
      + (endTime1 - startTime1)
      + " ms");
      long startTime2 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         variables[i] = new String("hello");
         variables[i] = variables[i].intern();		  
      }
      long endTime2 = System.currentTimeMillis();
      System.out.println("Creation time of" 
      + " String objects with intern(): " 
      + (endTime2 - startTime2)
      + " ms");
   }}

#以上程式碼實例輸出結果為:

Creation time of String literals : 0 ms
Creation time of String objects with &#39;new&#39; key word : 31 ms
Creation time of String objects with intern(): 16 ms

以上就是Java 實例- 字串優化的內容,更多相關內容請關注PHP中文網(www.php.cn)!



#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn