Monday, 17 November 2008

Speed of Exceptions

I wanted to check for duplicates as entries were being added to my Dictionary collection. I wasn't sure whether to use ContainsKey and check each and every time an item is added or simply sweep up after the Add method throws an Exception.

In reality the best solution will depend on the likely hit rate of duplicates but I thought I'd write the following code to test the speed differential when the hit rate is 100%.

Using ContainsKey
private void Button_Click(object sender, RoutedEventArgs e)
{
DateTime start = DateTime.Now;
for (int i = 0; i <= 1000; i++)
{
if (dummy.ContainsKey("Sunday"))
{
dummy["Sunday"]++;
}
}
DateTime end = DateTime.Now;
MessageBox.Show(end.Subtract(start).TotalMilliseconds.ToString());
}

Using Exceptions
private void Button_Click_1(object sender, RoutedEventArgs e)
{
DateTime start = DateTime.Now;
for (int i = 0; i <= 1000; i++)
{
try
{
dummy.Add("Sunday", 7);
}
catch
{
dummy["Sunday"]++;
}
}
DateTime end = DateTime.Now;
MessageBox.Show(end.Subtract(start).TotalMilliseconds.ToString());
}

Results
Using ContainsKey: 2 milliseconds
Using Exceptions: 5338 milliseconds

The ContainsKey adds about 0.04 milliseconds for the 1000 iterations - the rest is the down to the increment of the Dictionary int value.

No comments: