C # Cast exception

I came across some old code that throws and is empty, catching some exception exceptions (about 20 per trip :()

What if a performance hit occurs because of this? Do I have to worry about this or is the overhead just in try / catch

Surprisingly, there is no information on the topic of the effectiveness of exceptions with C #.

Thank you from your for real.

+6
performance c # exception
source share
5 answers

Exceptions will 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(); 

OK

 myType foo = obj as myType; if (foo != null) { foo.ExecuteOperation(); } 
+9
source share

This is bad for two reasons.

  • Exceptions are slow, there is a pretty strong blow. I don’t think it will take a whole millisecond, as Matt noted, but they are slow enough for you to avoid their normal work.
  • Unless you have a good reason, you should not catch empty exceptions. You just hide the problems. It is better that the program crashes than with its potentially dangerous errors.

If this is just a try { } finally { } group, then all is well - there is no overhead. However, try { } catch { } is potentially dangerous and potentially slow.

As for the documentation, this is pretty good: http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx#Don%27tuseexceptionhandlingasmeansofreturninginformationfromamethod18

Edit: Just realized that you said that you have exceptions for the exception, and not for detecting empty exceptions. In any case, if you are not dealing with IO, you probably want to avoid this for the sake of performance.

+1
source share

Exceptions are costly in terms of performance. The last time I measured them, they took about a full millisecond to throw and catch every exception.

Avoid using exceptions as a flow control mechanism.

0
source share

As others have noted, Exceptions are expensive on a roll. In some cases, they cannot be avoided.

In this case, it seems they can definitely be.

I would suggest using the as keyword before translating. This will tell you whether the casting succeeded or not, thereby completely eliminating the exception:

 object someObject; SomeType typedObject; // fill someObject typedObject = someObject as SomeType; if(typedObject == null) { // Cast failed } 
0
source share

If you have not encountered any performance issue, and this is the only way to make this algorithm, continue to use this method.

Perhaps, before you try to cast, you can see some if clauses if you can cast.

-one
source share

All Articles