Francois Beaussier & Aymeric Gaurat Apelli

Tuesday

The cost of an exception is about 6ms !

I have read quite a few times that exceptions were slow. I came to wonder about how slow they actually were? Is that big enough to care about it ? After all, hardware is pretty fast nowdays, isn't it?

Well it turns out that throwing and catching an exception takes about 6ms on my machine (Core Duo, 2ghz)

I you want to know why it takes 6ms, have a look at this fantastic post :)

Now, a few milliseconds, it does not look like a long time, but think about a web server, handling hundreds of requests at the same time. If each request uses a few Int.Parse that fails(or whatever code that may throw exceptions) , that could end up being quite significant.

This is a simplified version of the code I used (removed the loop to get an average value):

private void Execute()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();

    ThrowAndCatchException();

    sw.Stop();

    Console.WriteLine("Time taken: {0}ms", sw.ElapsedMilliseconds);
}

private void ThrowAndCatchException()
{
    try
    {
        throw new Exception();
    }
    catch (Exception) { }
    {
    }
}