Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple performance comparison between C# Dictionary and if / switch statements
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace DictionaryTest
{
class Program
{
/* CPU: AMD Ryzen Threadripper 1950x @ 4.0 Ghz
* Count: 100000000
* GetWeekDayNumberUsingIf, 400000000, 00:00:00.4316731
* GetWeekDayNumberUsingSwitch, 400000000, 00:00:00.4087778
* GetWeekDayNumberUsingDictionary, 400000000, 00:00:00.8983910
*/
/* https://dotnetfiddle.net/
* Count: 100000000
* GetWeekDayNumberUsingIf, 400000000, 00:00:01.9071346
* GetWeekDayNumberUsingSwitch, 400000000, 00:00:00.9301885
* GetWeekDayNumberUsingDictionary, 400000000, 00:00:02.7281431
*/
public static void Main(string[] args)
{
int count = 100000000;
var methodsToTest = new List<KeyValuePair<string, Func<DayOfWeek, int>>>()
{
new KeyValuePair<string, Func<DayOfWeek, int>>(nameof(GetWeekDayNumberUsingIf), GetWeekDayNumberUsingIf),
new KeyValuePair<string, Func<DayOfWeek, int>>(nameof(GetWeekDayNumberUsingSwitch), GetWeekDayNumberUsingSwitch),
new KeyValuePair<string, Func<DayOfWeek, int>>(nameof(GetWeekDayNumberUsingDictionary), GetWeekDayNumberUsingDictionary)
};
foreach (var method in methodsToTest)
{
int sum = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < count; i++)
{
DayOfWeek day = (DayOfWeek)(i % 7);
sum += method.Value(day);
}
stopwatch.Stop();
Console.WriteLine($"{method.Key}, {sum}, {stopwatch.Elapsed}");
}
}
static Dictionary<DayOfWeek, int> DayOfWeekNumbers = new Dictionary<DayOfWeek, int>()
{
{ DayOfWeek.Monday, 1 },
{ DayOfWeek.Tuesday, 2 },
{ DayOfWeek.Wednesday, 3 },
{ DayOfWeek.Thursday, 4 },
{ DayOfWeek.Friday, 5},
{ DayOfWeek.Saturday, 6 },
{ DayOfWeek.Sunday, 7 }
};
public static int GetWeekDayNumberUsingIf(DayOfWeek day)
{
if (day == DayOfWeek.Monday)
{
return 1;
}
else if (day == DayOfWeek.Tuesday)
{
return 2;
}
else if (day == DayOfWeek.Wednesday)
{
return 3;
}
else if (day == DayOfWeek.Thursday)
{
return 4;
}
else if (day == DayOfWeek.Friday)
{
return 5;
}
else if (day == DayOfWeek.Saturday)
{
return 6;
}
else if (day == DayOfWeek.Sunday)
{
return 7;
}
throw new ArgumentException();
}
public static int GetWeekDayNumberUsingSwitch(DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Monday: return 1;
case DayOfWeek.Tuesday: return 2;
case DayOfWeek.Wednesday: return 3;
case DayOfWeek.Thursday: return 4;
case DayOfWeek.Friday: return 5;
case DayOfWeek.Saturday: return 6;
case DayOfWeek.Sunday: return 7;
default: throw new ArgumentException();
}
}
public static int GetWeekDayNumberUsingDictionary(DayOfWeek day)
{
if (DayOfWeekNumbers.TryGetValue(day, out int value))
{
return value;
}
throw new ArgumentException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.