Here i am facing some performance difference with String and StringBuffer.
Firts i tried using StringBuffer, execution time difference is 0 secods...that means its fast..but i tried using String class ...it gives 10 mili seconds diff in execution of the loop.....but its only the first time i am execting the program...second time its execute within 0 mili seconds .......
what is the reason ??
[added code tags - Ilja]
[ June 25, 2004: Message edited by: Ilja Preuss ]
How many times did you try this out,
do you have a representative amount
of test runs?
ps I'm afraid this topic will be
moved from this forum
[ June 25, 2004: Message edited by: Gian Franco Casula ]
Second, you should never trust time measurement under, say, 100ms on Windows. As stated before, try to run your test 100 times, or even 1000 times in a loop, and compare the total times.
Adding on to a StringBuffer is [also] quite a bit faster than the + operator, which creates a new StringBuffer itself, appends both of the arguments, and converts the result back to a String
some other linx
Glen McCluskey et al
Hardwick's Java Optimization site
[these sites also have additional embedded links as well]
Well not really. However in cases where String + is faster, it's usually a very minor difference. In cases where StringBuffer is faster, it may be much, much faster. Adding N things to a StringBuffer is an O(N) operation. Adding them to a String via concatenation can be an O(N^2) operation. Which is a Bad Thing™ if N is big.
A good general rule of thum is: if you're adding to a stringlike thingy inside a loop, and the thingy gets bigger each time - use a StringBuffer. Otherwise, use String coincatenation with the + sign. The difference in performance is minor, and the + is usually more readable.
For what it's worth, if you can build up the entire String in one line, no loop, then the + will generally be at least as fast as using a StringBuffer. And if everything in the expression is a compile-time constant, then using + is almost certainly faster than StringBuffer, because all the work will be done at compile time.
Originally posted by Ilja Preuss:
Can you show us the benchmark code?
Also, what JDK did you run this on? This might heavily affect performance differences.
I just took Krishna Srinivasan's code and cleaned it up a bit. I'm not sure what JDK I used at home. But I tried it again at work with JDK 1.4.2_03 (on a faster PC that at home). These are the results:
So, the -O option doesn't do much. The ratio of 5 times faster holds.
One more tip: an important thing to do is to try wether swapping the order of execution, that is executing the StringBuffer version before the String version, makes a difference. It *could* have an impact because of incremental optimizations done by the Hotspot Engine.