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 pena开发者_StackOverflow社区lty or extra memory usage or anything else?)
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.
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.
精彩评论