Saturday, June 01, 2002

So I wrote a sample app that ran through each loop N number of times.  Which one do you think is faster?  Neither.  To run 100000 times, the foreach (with calls to StringBuilder.Append) loop took 1.927 seconds on a Pentium IV 1.4 GHZ machine with 512MB of RAM.  The simple for loop with calls to StringBuilder.Remove took 1.973 seconds on the same machine.  [Justin Rudd's Radio Weblog]

Justin did the right thing here.  Optimizations should be justified.  The thing is, from what I can tell, in the modified version, the StringBuilder had to do a copy of the original string s in its constructor, then move the characters around on top of the hyphens.  So it's not obvious to me that it would be any faster, given the extra copy operation (that's if my assumption's correct).

There's the larger picture to look at, too.  Justin did a profile of the code in question to determine which was faster, which is good, but you should also ask how often the code in question is called.  How often is this code called?  I remember a profile I ran a few years ago on screen scraping code I'd written.  I found that something like 90% of its time was spent evaluating regular expressions.  The best optimization I could do was replace some of my regex evals with simpler constructs, like simple string comparisons - anything else would still be dwarfed by the regex execution time. 

Another aspect of this comes into play when doing cross-process or networked applications.  The IPC or network I/O will dwarf any operation that stays in process memory.  At my job, our applications revolve around communicating with our mainframe, which has a response time of 1-4 seconds, depending on how far you are from Denver, and what network is connecting you.  It's pretty silly to dither over nanoseconds when you'll be waiting a full seconds for a response to a query.

10:26:12 AM  permalink Click here to send an email to the editor of this weblog. 


Stories
DateTitle
1/23/2003 Why XML?
8/13/2002 Resolution for IE and Windows problems
8/10/2002 Supporting VS.NET and NAnt
5/11/2002 When do you stop unit testing?
Contact
jabber: weakliem
YM: gweakliem
MSN: gweakliem@pcisys.net
email: Click here to send an email to the editor of this weblog.
Subscribe to "Gordon Weakliem's Weblog" in Radio UserLand.
Click to see the XML version of this web page.