T
Thomas Kellerer
Your test is not the same as a constant concatenation. Basically
String s = "some" + "thing";
(not in a loop or something)
will be expanded by the compiler. Not variable assignment elsewhere in the
code.
The test you have here is exactly the situation where programmer's
optimization *does* matter.
Regards
Thomas
String s = "some" + "thing";
(not in a loop or something)
will be expanded by the compiler. Not variable assignment elsewhere in the
code.
The test you have here is exactly the situation where programmer's
optimization *does* matter.
Regards
Thomas
Hendrik said:When the compiler expands the + macro to calls to StringBuffer and
combines adjacent literal strings, this becomes:
How do you explain these results:
Testing string concat...
Testing stringbuffer...
Results:
concat time: 2333ms total
buffer time: 20ms total
Does not look like ist becomes the same bytecode, though it should be identical. Using JDK 1.4.2 by the way...
This is the test class:
-- BEGIN CODE --
public class Test {
public static final int CYCLES = 10000;
public static void main(String argv[]) {
String s1 = new String("test");
String s2 = new String(" me");
String s3 = s1;
StringBuffer s4 = new StringBuffer(s1);
long time, time1, time2;
System.out.println("Testing string concat...");
time = System.currentTimeMillis();
for (int i=0; i<CYCLES; i++) {
s3 = s3 + s2;
}
time1 = System.currentTimeMillis() - time;
System.out.println("Testing stringbuffer...");
time = System.currentTimeMillis();
for (int i=0; i<CYCLES; i++) {
s4 = s4.append(s2);
}
time2 = System.currentTimeMillis() - time;
System.out.println("Results:");
System.out.println("concat time: " + time1 + "ms total");
System.out.println("buffer time: " + time2 + "ms total");
}
}
-- END CODE --