So sánh thời gian tạo String trong Java



Miêu tả vấn đề

Cách so sánh thời gian tạo String trong Java?

Giải pháp

Ví dụ sau minh họa cách so sánh thời gian tạo hai String, mà được tạo theo hai cách khác nhau trong Java.

public class StringComparePerformance{
   public static void main(String[] args){      
      long startTime = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         String s1 = "hello";
         String s2 = "hello"; 
      }
      long endTime = System.currentTimeMillis();
      System.out.println("Time taken for creation" 
      + " of String literals : "+ (endTime - startTime) 
      + " milli seconds" );       
      long startTime1 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         String s3 = new String("hello");
         String s4 = new String("hello");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Time taken for creation" 
      + " of String objects : " + (endTime1 - startTime1)
      + " milli seconds");
   }
}

Kết quả

Code trên sẽ cho kết quả sau. Kết quả có thể rất đa dạng.

Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 16 milli seconds

string_trong_java.jsp