Easy Tutorial
❮ Collection Array Home ❯

Java Example - String Performance Comparison Test

Java Examples

The following example demonstrates the creation of strings using two different methods and tests their performance:

StringComparePerformance.java File

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("Creating strings using String keyword" 
      + " : " + (endTime - startTime) 
      + " milliseconds");       
      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("Creating strings using String objects" 
      + " : " + (endTime1 - startTime1)
      + " milliseconds");
   }
}

The output of the above code example is:

Creating strings using String keyword : 6 milliseconds 
Creating strings using String objects : 14 milliseconds

Java Examples

❮ Collection Array Home ❯