Java Examples - String Performance Comparison Test
The following example demonstrates creating strings in two ways and testing 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 the 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:
通过 String 关键词创建字符串 : 6 毫秒 通过 String 对象创建字符串 : 14 毫秒Other Extensions
Java Examples