Factually incorrect. Creating new strings by concatenation requires reallocation because Strings are immutable in java. Using a Builder is over 700x faster:
Concat code: http://pastebin.com/CcezmJbf
Builder code: http://pastebin.com/Dd6kzcKa
Results, using JRE 7:
> time java concat data.blk Finished. java foo data.blk 170.08s user 1.52s system 102% cpu 2:48.12 total
> time java builder data.blk Finished. java builder data.blk 0.30s user 0.05s system 151% cpu 0.230 total
This is true, javac only replaces individual concatentations with use of a StringBuilder, so foo + bar + baz + "!" is fast, but performing a concatenation in a loop does multiple copies for each iteration. It (or the JIT) could conceivably do escape analysis to optimize simple cases like this, but it doesn't.
builder: http://hastebin.com/qadusoriqa.cs
What about the time to write the program?
About the same.
In special cases multiple string concatenations can be optimized into using a StringBuilder calls. Not in the general case.
Re:A Million Lines of Bad Code
by ExpiredLink on Saturday April 18, 2015 @04:29AM
(#9398730)
I'd say in the general case multiple string concatenations can be optimized. Not in special cases.
Re:A Million Lines of Bad Code
by hmottestad on Friday April 17, 2015 @04:16PM
(#9396936)
I built a string this way in java just 5 years ago. Still made it 100x times faster by using a StringBuilder.
So like 1ms down from 100ms? Either way a rounding error in the episode-of-LOST-average-duration timescale ;)
Re:A Million Lines of Bad Code
by hmottestad on Friday April 17, 2015 @05:33PM
(#9397316)
Why don't you give it a try yourself. Create a file with a high ratio of lines to length, and read it in using a loop and string concat, or builder. Do it with a builder first, when you get up to 1 minute, switch over to concat and see how long it takes.
No. Not in Java since 1999 or so.