C# Exception Optimization

This C# optimization article tests the performance of exceptions. It uses code motion to improve exception handling speed.

Exception handling can be made faster.

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. We also provide benchmarks.

 

 

Example. 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.

 

Note: The try-catch block is inside the inner loop in Method1, and outside the loop in Method2.

C# program that optimizes exception construct

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
	{
	}
    }
}

Results

2555.43 ns:    Method1
 674.29 ns:    Method2

Because no exceptions are thrown, the catch blocks are never reached. Method2, which has the try-catch outside the loop, is faster than Method1. If it doesn't affect runtime, hoisting exception handling outside a hot loop helps.

TryCatch

 

Summary. 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.

 

However: There is a notable difference in the program semantics. The drawbacks must be weighed against the benefits.