First of all, a disclaimer: I have experience in other languages, but am still learning the subtleties of C#
On to the problem... I am looking at some code, which u
Exceptions are slow, try not to use them.
See the answer I gave here.
Basically, Chris Brumme (who was on the CLR team) said they are implemented as SEH exceptions, so you take a big hit when they are thrown, have to suffer the penalties as they bubble through the OS stack. Its a truly excellent article and goes in depth in what happens when you throw an exception. eg.:
Of course, the biggest cost of exceptions is when you actually throw one. I’ll return to this near the end of the blog.
Performance. Exceptions have a direct cost when you actually throw and catch an exception. They may also have an indirect cost associated with pushing handlers on method entry. And they can often have an insidious cost by restricting codegen opportunities.
However, there is a serious long term performance problem with exceptions and this must be factored into your decision.
Consider some of the things that happen when you throw an exception:
Grab a stack trace by interpreting metadata emitted by the compiler to guide our stack unwind.
Run through a chain of handlers up the stack, calling each handler twice.
Compensate for mismatches between SEH, C++ and managed exceptions.
Allocate a managed Exception instance and run its constructor. Most likely, this involves looking up resources for the various error messages.
Probably take a trip through the OS kernel. Often take a hardware exception.
Notify any attached debuggers, profilers, vectored exception handlers and other interested parties.
This is light years away from returning a -1 from your function call. Exceptions are inherently non-local, and if there’s an obvious and enduring trend for today’s architectures, it’s that you must remain local for good performance.
Some people will claim that exceptions are not a problem, have no performance issues and are generally a good thing. These people get lots of popular votes, but they are just plain wrong. I've seen Microsoft staff make the same claims (usually with the technical knowledge usually reserved for the marketing department), but the bottom line from the horse's mouth is to use them sparingly.
The old adage, exceptions should only be used for exceptional circumstances, is as true for C# as it is for any other language.