Reputation: 2065
Stumbled on some old code that is throwing and empty catching some cast exceptions (about 20 per trip :( )
What if any is the performance hit were taking due to this? Should I be worried about this or is the overhead simply in the try / catch
Surprisingly lacking information on the topic of exception performance with C#.
Thanks, from yours truly.
Upvotes: 7
Views: 3647
Reputation: 24403
The exceptions are going to slow you down more than most average lines of code. Instead of casting and then catching the exception, do a check instead. For example
BAD
myType foo = (myType)obj;
foo.ExecuteOperation();
GOOD
myType foo = obj as myType;
if (foo != null)
{
foo.ExecuteOperation();
}
Upvotes: 11
Reputation: 7096
That's bad for two reasons.
If they're just try { } finally { }
groups, then it's all good -- there's no overhead there. However, try { } catch { }
is both potentially dangerous and potentially slow.
As for documentation, this is pretty good: http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx#Don%27tuseexceptionhandlingasmeansofreturninginformationfromamethod18
Edit: just realized you said empty catching exceptions, not catching empty exceptions. Either way, unless you're dealing with IO, you probably want to avoid doing that for performance's sake.
Upvotes: 1
Reputation: 245399
As others have mentioned, Exceptions are expensive when thrown. In some cases they can't be avoided.
In this case, though, it sounds like they definitely can be.
I would suggest using a the the as
keyword before the cast. That will tell you if the cast succeeded or not thus avoiding the Exception altogether:
object someObject;
SomeType typedObject;
// fill someObject
typedObject = someObject as SomeType;
if(typedObject == null)
{
// Cast failed
}
Upvotes: 0
Reputation: 13019
If you haven't encountered any performance problem and this is the only way you have to do that algorithm continue to use this method.
Maybe before trying to cast you could see with some if
clauses if you could do the cast.
Upvotes: -1
Reputation: 10389
Exceptions are expensive, performance-wise. Last time I measured these, they were taking about a full millisecond to throw and catch each exception.
Avoid using exceptions as a flow control mechanism.
Upvotes: 0