Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance Cost Of 'try' in C#

Tags:

c#

exception

I know that exceptions have a performance penalty, and that it's generally more efficient to try and avoid exceptions than to drop a big try/catch around everything -- but what about the try block itself? What's the cost of merely declaring a try/catch, even if it never throws an exception?

like image 496
Merus Avatar asked May 15 '09 04:05

Merus


People also ask

Does Try Catch affect performance?

In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.

Is try catch costly?

Using try catch adds performance cost, but it isn't a major performance cost. Isn't it best to use try catch block as much as possible? No, it is best to use try catch block when makes sense. The performance cost depends on which compiler you use.

Does try catch have overhead?

There has to be an overhead for try/catch blocks so that the CLR can handle the exceptions. C# runs on the . NET CLR(a virtual machine).

Do try catch blocks hurt performance C++?

Does it mean that having a try block reduces performance due to the extra task of "inspection" during run time? Typically yes, but unless it's a time-critical, called-a-million-times, must-be-really-fast portion of code, I wouldn't base my decision of whether or not to use exceptions on this.


2 Answers

The performance cost of try is very small. The major cost of exception handling is getting the stack trace and other metadata, and that's a cost that's not paid until you actually have to throw an exception.

But this will vary by language and implementation. Why not write a simple loop in C# and time it yourself?

like image 169
JSBձոգչ Avatar answered Sep 21 '22 04:09

JSBձոգչ


Actually, a couple months ago I was creating an ASP.NET web app, and I accidentally wrapped a try / catch block with a very long loop. Even though the loop wasn't generating every exceptions, it was taking too much time to finish. When I went back and saw the try / catch wrapped by the loop, I did it the other way around, I wrapped the loop IN the try / catch block. Performance improved a LOT. You can try this on your own: do something like

int total;

DateTime startTime = DateTime.Now;

for(int i = 0; i < 20000; i++)
{
try
{
total += i;
}
catch
{
// nothing to catch;
}
}

Console.Write((DateTime.Now - startTime).ToString());

And then take out the try / catch block. You'll see a big difference!

like image 39
Carlo Avatar answered Sep 19 '22 04:09

Carlo