A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/string_performance.htm below:

How to compare performance of string creation in Java

How to compare performance of string creation in Java Problem Description

How to compare performance of string creation?

Solution

Following example compares the performance of two strings created in two different ways.

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

The above code sample will produce the following result.The result may vary.

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

java_strings.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4