Are exceptions fast? Here we see a method that carefully tests for null (and thus does not need exception handling) and a method that uses try and catch.
using System;
using System.Diagnostics;
class Program
{
static int GetA(int[] arr)
{
if (arr != null)
// Check for null.
{
return arr[0];
}
else
{
return 0;
}
}
static int GetB(int[] arr)
{
try
{
return arr[0];
}
catch
// Catch exceptions.
{
return 0;
}
}
const int _max = 1000000;
static void Main()
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int count = 0;
var s1 = Stopwatch.StartNew();
// Version 1: use if-statement to handle errors.
for (int i = 0; i < _max; i++)
{
int v = GetA(arr);
if (v == 5)
{
count++;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use try-catch to handle errors.
for (int i = 0; i < _max; i++)
{
int v = GetB(arr);
if (v == 5)
{
count++;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
1.95 ns: GetA, if check
3.91 ns: GetB, try-catch