Could someone explain to me what is going on here...
Scenario 1
This:
// around 50ms
for (int i = 0; i < 3000000; i++) {
String str = new String();
}
... is more time consuming than this:
// around 25ms
for (int i = 0; i < 3000000; i++) {
String str = new String("");
}
Scenario 2
This:
String str = new String(); // around 3000ns
is less time consuming than this:
String str = new String(""); // around 5000ns
Why is calling the empty String() constructor more time consuming in scenario 1, but not in scenario 2? I had a look at the doc for String() and String(String original), but I could see no optimization there. Is this optimization (if it indeed is optimization) done somewhere else?
Updates:
How I'm timing this:
long start = System.nanoTime();
//doing stuff here
long elapsedTime = System.nanoTime() - start;
My system:
Windows 7 x64, using Java 7 and Eclipse