Tech Tock

Time is of the essence.

“Throwing exceptions can negatively impact performance” – Believe it.

I was parsing a ton of strings (don’t ask) and catching FormatException (a lot).  By a ton, I mean several hundred thousand parsed into dates and doubles. By a lot of exceptions, I mean 90% of the data was blank.  Let’s just call it sparse.  The process was taking about 30 seconds.  I changed the code to avoid the FormatException:

    if (!string.IsNullOrEmpty(value))
        o = double.Parse(value);

Performance improved by at least 10 times to under 3 seconds.  Problem solved.

Turns out this is a bona fide pattern.  The tester-doer pattern.


December 1, 2009 - Posted by | Uncategorized | , , , , , ,


  1. bool success = double.TryParse(value, out o);

    Comment by Andre de Cavaignac | December 2, 2009 | Reply

    • Thanks Andre.

      This is good to remember.

      I’m on the fence as to whether this is better. Since most (all so far) of my problem comes from empty data, checking for that specifically may make more sense.

      Using TryParse I’d still have to do the same extra work to handle cases for if the parse failed because of empty/null or invalid formatting.

      Comment by goldmanalpha | December 2, 2009 | Reply

  2. TryParse is your friend … it was added in bcl 2.0 for exactly this reason. Pre 2.0 the only way to detect parsing failure was to catch the exception. Which has significant impact of perf.

    Either way, testing for null or empty string is suggested.
    Whether null or empty is valid is dependent on your use case.

    You could wrap TryParse in a helper function that returns a nullable type.

    double? o = Utils.DoubleParse(s);

    You’re always going to need to test for success or failure, it’s just choosing a way.

    Choices are: Catch exception; test result of TryParse; wrap it to return nullable.

    Comment by Adam Miller | December 3, 2009 | Reply

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: