K
Kamal Advani
Hello,
Sorry if this topic has been beaten to death, or if there's an FAQ
(kindly point me to it); I'm a bit baffled by the following behaviour:
-----------
public void testTiming() {
long start, stop;
start = System.currentTimeMillis();
for (int i=0; i < 1000; i++) {
getStrBuff(""+new Date()+new Date()+new Date()+new Date());
}
stop = System.currentTimeMillis();
System.out.println("strbuff took (in ms): " + (stop - start));
start = System.currentTimeMillis();
for (int i=0; i < 1000; i++) {
getStrCat(""+new Date()+new Date()+new Date()+new Date());
}
stop = System.currentTimeMillis();
System.out.println("strcat took (in ms): " + (stop - start));
}
private String getStrBuff(String x) {
return new StringBuffer("x is ").append(x).toString();
}
private String getStrCat(String x) {
return "x is " + x;
}
---------
// Output
strbuff took (in ms): 1573
strcat took (in ms): 130
---------
Why does the StringBuffer version run significantly slower (consistent
proportion across multiple runs are obtained)?
I can understand if they're String literals concatenated together, or
Strings whose values are well known in advance, allowing the compiler to
optimise at compile time into a single literal for e.g.; in this case,
dates can only be obtained at runtime - wouldn't that imply that the +
version will create StringBuffers internally?
Thanks.
Sorry if this topic has been beaten to death, or if there's an FAQ
(kindly point me to it); I'm a bit baffled by the following behaviour:
-----------
public void testTiming() {
long start, stop;
start = System.currentTimeMillis();
for (int i=0; i < 1000; i++) {
getStrBuff(""+new Date()+new Date()+new Date()+new Date());
}
stop = System.currentTimeMillis();
System.out.println("strbuff took (in ms): " + (stop - start));
start = System.currentTimeMillis();
for (int i=0; i < 1000; i++) {
getStrCat(""+new Date()+new Date()+new Date()+new Date());
}
stop = System.currentTimeMillis();
System.out.println("strcat took (in ms): " + (stop - start));
}
private String getStrBuff(String x) {
return new StringBuffer("x is ").append(x).toString();
}
private String getStrCat(String x) {
return "x is " + x;
}
---------
// Output
strbuff took (in ms): 1573
strcat took (in ms): 130
---------
Why does the StringBuffer version run significantly slower (consistent
proportion across multiple runs are obtained)?
I can understand if they're String literals concatenated together, or
Strings whose values are well known in advance, allowing the compiler to
optimise at compile time into a single literal for e.g.; in this case,
dates can only be obtained at runtime - wouldn't that imply that the +
version will create StringBuffers internally?
Thanks.