Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception efficiency when nothing is thrown

I have a hypothetical question about the efficiency consequences of using exception handling in situations where no exceptions are thrown.

First take a look at this C#:

int simpleSimon, cautiousCarol, dangerousDave;

try
{
    simpleSimon = int.Parse("fail");
}
catch
{
    simpleSimon = 1;
}

try
{
    cautiousCarol = int.Parse("1");
}
catch
{
    cautiousCarol = 1;
}

dangerousDave = int.Parse("1");

I am confident that Dave's code will be the fastest/most efficient; while Simon will incur a large penalty for throwing an exception.

But what about Carol? As she throws no exceptions does she incur a penalty? If so, then what kind and how large? (Performance penalty or extra memory usage or anything else?)

like image 652
Buh Buh Avatar asked Feb 16 '11 18:02

Buh Buh


Video Answer


2 Answers

No significant penalty for Carol. Only certain jumps will be registered and executed if needed.

As a hint, use int.TryParse(...) to avoid situations like this.

like image 159
Daniel A. White Avatar answered Oct 19 '22 01:10

Daniel A. White


It is a JIT implementation detail. The x86 jitter must setup 16 bytes in the stack frame to help the CLR find the proper catch block in case the exception is thrown. That should take about 3 nanoseconds. No work at all for the x64 jitter, exception filtering is implemented differently on the 64-bit version of Windows (table based instead of stack based). The extra memory required is about equivalent (code vs table data).

None of this should ever matter with code like this, converting a string to an integer is an I/O operation. The cost of getting the data in the first place is an easy 3 or 4 orders of magnitude larger than any parsing you do. And you'd of course use TryParse() if you don't trust the source of the data. Processing an exception is quite expensive.

like image 30
Hans Passant Avatar answered Oct 19 '22 00:10

Hans Passant