Robustness can be trying in terms of performance!!


Robustness is one of the underlying principles for all software projects and most languages provide support for making the software as robust as possible. Exception handling is one of the most common mechanisms for providing robustness and elegant way of handling exceptional situations.

But as they say “Nothing comes for free in this world”, the robustness comes at a cost. Let’s examine the following two snippets of code:

Snippet 1

void func1_recursive(int nInput)


{
try
{
if (j<1000)
{
j++;
func1_recursive(j);
}
else
{
j = 0;
}
}
catch(int& i)
{
}
catch(…)
{
}
}
int func_with_TryCatch()
{
int nStart = GetTickCount();
j=0;
for (int i=0;i<20000;i++)
{
func1_recursive(i);
}

int nStop = GetTickCount();
return nStop – nStart;
}

Snippet 2
void func2_recursive (int nInput)
{
if (j<1000)
{
j++;
func2_recursive(j);
}
else
{
j = 0;
}
}

int func_without_TryCatch()
{
int nStart = GetTickCount();
j=0;
for (int i=0;i<20000;i++)
{
func2_recursive(i);
}
int nStop = GetTickCount();
return nStop – nStart;
}

The two above functions were executed on an Intel (R) Pentium D CPU 3.40 GHz machine with 4 GB RAM. func_with_TryCatch() took 1704 ms whereas func_without_TryCatch took 1234 ms, which is about 30% faster. Scott Meyers notes that throwing an exception is about “three orders of magnitude slower” than a normal return. Programs using exceptions are about “5-10% larger and 5-10% slower.”

As per Kevin Frei of the Visual C++ Code Generation & Tools team, Exception Handing has a performance cost which is not always measurable and depends on usage. Some of the reasons that he attributes to the cost are Usage Penalty (cost of the Exception Handling block itself), Cost of entering a protected region (the individual try catch blocks) and Cleanup Costs (finally invocation and C++ object destructors).

For more details check out: http://www.nwcpp.org/Downloads/2006/ehc.ppt

Morals of the Story

1) Use exception handling only where it is required. Do not use exceptions for normal program flow.

2) Understand the cost of using exception handling particularly in iterative functions and in functions called in a loop.

Cheers!

Ram

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s