Optimizing with a narrow scope
  Posted March 25, 2004    PermaLink    Comments (0)  

When optimizing stuff you need to keep a rather large scope to make sure you aren't really making things worse. Consider this entry on Strings.

Based on what the entry is discussing at the best you are optimizing byte code alone. What needs to also be considered is the true cost of the virtual method being called, String.concat(String) vs. StringBuffer.append(String). Those 8 lines in bytecode you save will be more than made up in heap thrash and array copying. (But if it's a J2ME environment, it may be valuable enough, even caveats have caveats, time vs memory is a tradeoff not a rule).

For the case of two strings this is the same performance as common StringBuffer tricks, but once you go to three or more IMHO using a StringBuffer or merging all additions to one line is the best way to go. Concat creates a new char buffer big enough for itself and the item being concated, so for N strings N-1 extra buffers are created, whereas a string buffer only creates a new one on size violations, so N-1 is the worst case.

And this is a worst case, when dealing with multi KB or multi MB strings the hit is huge with lots of GC thrash for each new string in concats or simple "+" operations. If you can cram all of the strings into one <RVALUE> you will get StringBuffer/StringBuilder for free, otherwise make one and use it yourself, your heap will thank you.