Monday, November 14, 2011

Exceptions - More Expensive Than You Might Think

So, everybody knows that you shouldn't use exceptions in control logic right?  Meaning, you shouldn't expect exceptions to be thrown and you shouldn't plan on reacting to them under normal code execution circumstances, right?  Exceptions are, well, exceptional.  They are the exception, not the norm.

Recently I wrote some code where I violated this rule in a manner that seemed innocent enough to me.  I wrote an extension method for IDataReader that looked like this:










It's purpose was to check if a value exists in a data reader before trying to access it.  I was looping through a data reader to populate an object, and I was doing a lot of converts (ToBoolean, ToDateTime, ToDecimal, etc), so I wanted to make sure the values existed.  The column names matched property names on my object.  I was looping through the properties of the object using reflection, and not all the properties were being populated from the database call that populated the data reader, so an exception was being thrown quite often in TryGetObject, because a lot of the data didn't exist.

I had written a web service method that called the database stored procedure I was using.  Initially I noticed this was taking ~2.5 seconds to complete which I though was ridiculous.  After looking through my code I saw that this was the only "wrong" thing I was doing, so I replaced it with a method that loops through all the columns of the data reader to check if one exists.  This took my execution time down to ~150ms.  That's a decrease of well over ten-fold.

So the moral of the story is:  Exceptions are more expensive than you might think. 



No comments:

Post a Comment