Skip to content

Instantly share code, notes, and snippets.

@wcharczuk
Created November 9, 2011 23:19
Show Gist options
  • Save wcharczuk/1353509 to your computer and use it in GitHub Desktop.
Save wcharczuk/1353509 to your computer and use it in GitHub Desktop.
C# Exception performance hit example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionsAreBad
{
class Program
{
static void Main(string[] args)
{
var t1 = new Task(() =>
{
DateTime started = DateTime.Now;
var thing = new LongRunningThing();
int count = 0;
for (;;)
{
try
{
thing.DoStuff();
}
catch { }
var now = DateTime.Now;
if (now - started > new TimeSpan(0, 1, 0))
{
Console.WriteLine("normal count: " + count.ToString());
Console.WriteLine(String.Format("normal avg time: {0}ms", (now - started).TotalMilliseconds / count));
break;
}
else
count++;
}
});
var t2 = new Task(() =>
{
DateTime started = DateTime.Now;
var thing = new LongRunningThingWithException();
int count = 0;
for (;;)
{
try
{
thing.DoStuff();
}
catch { }
var now = DateTime.Now;
if (now - started > new TimeSpan(0, 1, 0))
{
Console.WriteLine("exception count: " + count.ToString());
Console.WriteLine(String.Format("exception avg time: {0}ms", (now - started).TotalMilliseconds / count));
break;
}
else
count++;
}
});
t1.Start(); t2.Start();
Task.WaitAll(t1, t2);
Console.WriteLine("done.");
Console.ReadKey();
}
}
public class LongRunningThing
{
public virtual void DoStuff()
{
System.Threading.Thread.Sleep(100);
}
}
public class LongRunningThingWithException : LongRunningThing
{
public override void DoStuff()
{
base.DoStuff();
throw new Exception("this is an exception. hooray!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment