Error Prevention is Way Better than a Cure when it Comes to .Net Error Handling

Here’s a fun little .Net speed optimization I found out today:

(In both of these “Reader” is a DataReader which I’m using to loop through a set of database records.)

Code #1:

dim myValue as string

While Reader.Read()
  Try
     myValue = Reader("FieldWhichMayNotExist")
  Catch
     myValue = "This is a default value"
  End Try
end While

And here’s Code #2:

dim myValue as string

dim fieldExists as Boolean = 
FigureOutIfFieldExists(Reader, "FieldWhichMayNotExist")

While Reader.Read()
  if fieldExists then
     myValue = Reader("FieldWhichMayNotExist")
  else
     myValue = "This is a default value"
  end if
End While

So, what’s the big difference? The first one traps for the field not existing and inserts a default value if so; and the second one wastes a bunch of time going through a routine to see if the field exists, then loops through and uses the result of that first scan to use either the field value or the default value accordingly.

You might think that the two would run in similar amounts of time–or maybe even Code #1 would be a little faster, since it didn’t waste a few precious milliseconds scanning to see if the field exists.

But here’s the shocker:  Code sample #2 runs about 20 times faster than code sample #1, since it doesn’t need to deal with the whole .Net exception architecture. In the case of the actual code upon which this was based, it meant the difference between being able to insert 630,000 records in around 100 seconds, vs. more than an hour.

Exception handling: it’s more expensive than you think–particularly inside loops. Prevention in this case was worth 20 times more than a cure.

Leave a Reply

Your email address will not be published. Required fields are marked *