简体   繁体   中英

C# Cast Exception

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.

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();
}

That's bad for two reasons.

  1. Exceptions are slow, there is quite a performance hit. I don't think it'd take an entire millisecond as Matt pointed out, but they are slow enough that you want to avoid them in normal operation.
  2. Unless you have a good reason, you shouldn't catch empty exceptions. You're just hiding problems. Better that a program crashes than that it carries on with potentially dangerous bugs.

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.

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.

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM