4 ms·
> Building a string with a series of concatenations like this is extremely inefficient No. Not in Java since 1999 or so.
by ExpiredLink 11y ago
> Building a string with a series of concatenations like this is extremely inefficient
No. Not in Java since 1999 or so.
- hmottestad 11y agoI built a string this way in java just 5 years ago. Still made it 100x times faster by using a StringBuilder.
- reinhardt 11y agoSo like 1ms down from 100ms? Either way a rounding error in the episode-of-LOST-average-duration timescale ;)
- hmottestad 11y agoWhy 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.
- Tossrock 11y agoFactually 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 http://pastebin.com/CcezmJbf Builder code: http://pastebin.com/Dd6kzcKa 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
- Sevzinn 11y agoWhat about the time to write the program?
- Tossrock 11y agoAbout the same.
- jmgao 11y agoThis 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 http://hastebin.com/qadusoriqa.cs concat: http://hastebin.com/nasukuxemi.cs http://hastebin.com/nasukuxemi.cs
- army 11y agoIn special cases multiple string concatenations can be optimized into using a StringBuilder calls. Not in the general case.
- ExpiredLink 11y agoI'd say in the general case multiple string concatenations can be optimized. Not in special cases.