Home  >  Article  >  Java  >  Java Example - String Optimization

Java Example - String Optimization

黄舟
黄舟Original
2017-02-22 09:49:111352browse

The following example demonstrates optimizing strings through the String.intern() method:

//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");
   }}

The output result of the above code example is:

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

The above is the content of Java Example-String Optimization. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn