C# Exception Optimization

Performance optimization

How can you improve the performance of exception handling in some C# programs? If you have an exception handling construct (try/catch) in an inner loop, you could hoist it to the outside of the loop. We demonstrate this code motion and also provide benchmarks.

Exception code motion

This program introduces two methods we benchmark: Method1 and Method2. These methods are semantically different in only one way—if an exception is thrown, the entire loop terminates in Method2 but not in Method1. The try/catch block is inside the inner loop in Method1, and outside the loop in Method2.

Program that optimizes exception construct [C#]

using System;
using System.Diagnostics;

class Program
{
    const int _max = 1000000;
    static void Main()
    {
	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    Method1();
	}
	s1.Stop();
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    Method2();
	}
	s2.Stop();
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.Read();
    }

    static void Method1()
    {
	for (int i = 0; i < 1000; i++)
	{
	    try
	    {
		int value = i * 100;
		if (value == -1)
		{
		    throw new Exception();
		}
	    }
	    catch
	    {
	    }
	}
    }

    static void Method2()
    {
	try
	{
	    for (int i = 0; i < 1000; i++)
	    {
		int value = i * 100;
		if (value == -1)
		{
		    throw new Exception();
		}
	    }
	}
	catch
	{
	}
    }
}

Result

2555.43 ns
674.29 ns

Results. Because no exceptions are thrown, the catch blocks are never reached. Method2, which has the try/catch outside the loop, is several times faster than Method1. If it doesn't greatly affect the runtime of a program, hoisting the exception handling outside a hot loop is an effective optimization.

Summary

.NET Framework information

In the C# language and .NET Framework, exception handling is relatively slow even if no exceptions are thrown. Code motion, which is a subset of optimization that includes hoisting expressions outside of loops, yields a performance gain; there is a notable difference in the program semantics however.

Exception Handling
.NET