2021-04-18 15:25  阅读(161)
文章分类:Java 基础实战 文章标签:JavaJava 教程
©  原文作者:w3cschool 原文地址:https://www.w3cschool.cn/java/java-examples.html

以下实例演示了通过 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 '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 ms
    Creation time of String objects with 'new' key word : 31 ms
    Creation time of String objects with intern(): 16 ms
    
点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Java 实例 – 字符串优化
上一篇
Java 实例 – 字符串性能比较测试
下一篇
Java 实例 – 字符串格式化