« Web Service aren't Distributed Objects?! | Main | Don't Laugh, I've Done the Commando Pattern »

Optimizing with a narrow scope

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

Listed below are links to weblogs that reference Optimizing with a narrow scope:

» String concatenation. Disclaimer. from Euxx
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 [Read More]

» String concatenation. Disclaimer. from Euxx
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 [Read More]

About

This page contains a single entry from the blog posted on March 25, 2004 4:09 AM.

The previous post in this blog was Web Service aren't Distributed Objects?!.

The next post in this blog is Don't Laugh, I've Done the Commando Pattern.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33