Hi Friends,
Can any of you pls tell me (in detail) which of the following options will be faster?

Option 1:

int fun()
{
    if( !cm_aObject )
         return -1;
    return cm_aObject->getNum();
}

Option 2:

int fun()
{
    try{
          return cm_aObject->getNum();
    }catch(...){
          return -1;
    }
}

Thanx,
Amit

Recommended Answers

All 4 Replies

Option 2 is slower because there is a lot more code to be executed.

That doesn't mean you should avoid exception handling; in fact the performance loss is so minimal, it's hardly worth taking that into account when trying to decide when and where to use exception handling. Option 2 is by far the most robust.

Thanx to both of you. :)

Amit

in fact the performance loss is so minimal, it's hardly worth taking that into account when trying to decide when and where to use exception handling.

not true. exceptions are designed with the idea that
a. you do not have to pay a high performance penalty in the event of there being no error
b. if there is an error, you are willing to spend time recovering from it.
c. exceptions, as the name suggests, are used to indicate exceptional conditions that do not occur in the normal course of events.

Ancient Dragon's statement is accurate; the easiest way to check it out is
a. generate the assembly code for both versions and have a look at it.
b. write a test driver and time the performance on your implementation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.