Here is a Java Program to compare performance of string creation
Output of Above Java Program
Time taken for creation of String literals : 2 milli seconds
Time taken for creation of String objects : 5 milli seconds
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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" ); } } |
Output of Above Java Program
Time taken for creation of String literals : 2 milli seconds
Time taken for creation of String objects : 5 milli seconds