The new keyword definitely consumes more time when compared to direct initializing the value to a String object.
The following illustrates the time consumed by both the mechanisms. These values may vary from environment to environment. Code snippet:
public class StringCreationAndPerformance
{
public static void main(String args[])
{
StringCreationAndPerformance stringCreationAndPerformance = new StringCreationAndPerformance();
stringCreationAndPerformance.proceed();
}
private void proceed()
{
long startTime = 0, endTime = 0;
int numberOfObjects = 10000000;
startTime = System.currentTimeMillis();
System.out.println("Start time: With new operator: " + startTime);
for (int i=0;i {
String newString = new String("With new");
}
endTime = System.currentTimeMillis();
System.out.println("End time: With new operator: " + endTime);
System.out.println("Total time: With new operator: " + (endTime-startTime));
startTime = System.currentTimeMillis();
System.out.println("Start time: With = operator: " + startTime);
for (int i=0;i {
String newString = "Without";
}
endTime = System.currentTimeMillis();
System.out.println("End time: With = operator: " + endTime);
System.out.println("Total time: With = operator: " + (endTime-startTime));
}
}
/*
Expected output:
[root@mypc]# java StringCreationAndPerformance
Start time: With new operator: 1506426921408
End time: With new operator: 1506426921439
Total time: With new operator: 31
Start time: With = operator: 1506426921440
End time: With = operator: 1506426921443
Total time: With = operator: 3
*/