首页  >  文章  >  Java  >  Java 实例 - 字符串优化

Java 实例 - 字符串优化

黄舟
黄舟原创
2017-02-22 09:49:111327浏览

以下实例演示了通过 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