3 ms·
Factually incorrect. Creating new strings by concatenation requires reallocation because Strings are immutable in java. Using a Builder is over 700x faster: Co
by Tossrock 12y ago
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 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 12y agoWhat about the time to write the program?
- Tossrock 12y agoAbout the same.
- jmgao 12y 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