Home > Java > javaTutorial > body text

Java Example - String Optimization

黄舟
Release: 2017-02-22 09:49:11
Original
1344 people have browsed it

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");
   }}
Copy after login

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
Copy after login

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)!



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template