Created
November 9, 2011 23:19
-
-
Save wcharczuk/1353509 to your computer and use it in GitHub Desktop.
C# Exception performance hit example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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