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.

TrackBack
  String concatenation. Disclaimer.
Excerpt: My last post gave a wrong impression about what I was trying to say. That concrete example were given for concatenation of TWO strings as it given in Java snippets. Surely for more then two strings concatenation it better to use StringBuffer. However p
Weblog: Euxx
Tracked: March 26, 2004 12:05 PM
 
TrackBack
  String concatenation. Disclaimer.
Excerpt: My last post gave a wrong impression about what I was trying to say. That concrete example were given for concatenation of TWO strings as it given in Java snippets. Surely for more then two strings concatenation it better to use StringBuffer. However p
Weblog: Euxx
Tracked: March 26, 2004 08:16 PM
 
Trackback URL
  TrackBack URL for this entry:
http://shemnon.com/cgi-bin/mt/mt-tb.cgi/137
 
Post Comment
 

Thanks for signing in, . Now you can comment. (sign out)

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


Remember me?


Name:
Email Address:
URL: