Alex Rivera | Logout

How much more expensive is an Exception than a return value?

Asked 2009-08-15T16:28:04.113
17

Is it possible to change this code, with a return value and an exception:

public Foo Bar(Bar b)
{
   if(b.Success)
   {
      return b;
   }
   else
   {
      throw n.Exception;
   }
}

to this, which throws separate exceptions for success and failure

public Foo Bar(Bar b)
{
   throw b.Success ? new BarException(b) : new FooException();
}

try
{
   Bar(b)
}
catch(BarException bex)
{
   return ex.Bar;
}
catch(FooException fex)
{
   Console.WriteLine(fex.Message);
}
Edit
Report

2 Answers

4

You can find a lot of useful information about this in the answers to this question, including one answer with 45 up-votes How slow are .net exceptions?

answered 2009-08-15T16:41:46.893
1

In some recent real work performance analysis, we found that tons of exceptions on lower end machines had a critical effect on the application performance, so much so that we are devoting a few weeks to go through and adjust the code to not throw so many.

When I say a critical effect, it was in the ballpark of spiking the dual core CPU up to 95% on the single CPU core the application was using.

answered 2009-08-15T16:35:19.073

Your Answer