This question has been asked many times on StackOverflow but none of them were based on performance.
In Effective Java book it's given that
If
String s = new String("stringette");
occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly.The improved version is simply the following:
String s = "stringette";
This version uses a single String instance, rather than creating a new one each time it is executed.
So, I tried both and found significant improvement in performance:
for (int j = 0; j < 1000; j++) {
String s = new String("hello World");
}
takes about 399?372 nanoseconds.
for (int j = 0; j < 1000; j++) {
String s = "hello World";
}
takes about 23?000 nanoseconds.
Why is there so much performance improvement? Is there any compiler optimization happening inside?
See Question&Answers more detail:os