Grieve (grieve) wrote,
Grieve
grieve

The Cost of Exceptions

The other day at work I saw the following C++ code snippet:
CriticalSection.lock();
SomeFunc();
CriticalSection.unlock();

I noted that if SomeFunc() threw an exception the CriticalSection would remain locked. The writer of the code stated that they did not use exceptions. I asked why, and he stated that it was a performance issue.

I couldn't just let that go, so I wrote a test. In the test I have two functions that both add two parameters together and return the sum. The first function returns 0 if the sum is greater than 100. The second function throws an exception if the sum is greater than 100.

I call the first function 1 million times, measure the time it takes, and divide that time by 1 million to get the average time per call. On the Dell Precision 690 it took 0.010 microseconds per function call.

I call the second function 1 million times, with parameters which ensure it will not throw, and the average time per call is 0.011 microseconds per function call.

I call the second function 1 million times, with parameter which ensure it will throw every time, and the average time per call is 2.1 microseconds per function call.

There are a lot of things this test does not measure, such as code size, speed of nested functions etc, but overall it looks as if the overhead for exceptions is very small, until you actually throw an exception. And as we all know exceptions should be exceptional (therefore rare).

Using exceptions has its own problems, but citing poor performance as a reason not to use them is just laziness.
Tags: programming
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 2 comments