通过 String.intern() 方法来优化字符串

来源:互联网 发布:3ds max模型优化 编辑:程序博客网 时间:2024/05/22 00:26


以下实例演示了通过 String.intern() 方法来优化字符串:

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 'new' 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 msCreation time of String objects with 'new' key word : 31 msCreation time of String objects with intern(): 16 ms



0 0
原创粉丝点击