using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace SwitchVsDictionaryBenchMark { class Program { private static readonly Dictionary dictWithStrings = new Dictionary(3); private static readonly Dictionary dictWithInts = new Dictionary(20); private const int MillisecondsSleep = 10; static void Main(string[] args) { dictWithStrings.Add("Zero", Sleep); dictWithStrings.Add("One", Sleep); dictWithStrings.Add("Two", Sleep); const int iterations = 1000; var tsSwitch = Benchmark( () => SwitchTest("One"), iterations); var tsDict = Benchmark( () => DictTest("One"), iterations); Console.WriteLine("Difference in MS dict - switch with strings: {0}", tsDict - tsSwitch); var r = new Random(); var switchWithIntMs = Benchmark(() => SwitchWithIntTest(r.Next(0, 20)), iterations); for (int i = 0; i < 20;i++ ) dictWithInts.Add(i, Sleep); var dictWithIntsMs = Benchmark(() => DictWithIntTest(r.Next(0, 20)), iterations); Console.WriteLine("Difference in MS - dict - switch with ints: {0}", dictWithIntsMs - switchWithIntMs); Console.ReadLine(); } private static long Benchmark(Action act, int iterations) { GC.Collect(); act.Invoke(); // run once outside of loop to avoid initialization costs Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { act.Invoke(); } sw.Stop(); Console.WriteLine("MS per iteration: " + (sw.ElapsedMilliseconds / iterations).ToString()); Console.WriteLine("total Elapsed MS: " + sw.ElapsedMilliseconds.ToString()); return sw.ElapsedMilliseconds; } private static void SwitchTest(string testCase) { switch (testCase) { case "Zero": Sleep(); break; case "One": Sleep(); break; case "Two": Sleep(); break; default: Sleep(); break; } } private static void DictTest(string testCase) { Action command; if (dictWithStrings.TryGetValue(testCase, out command)) { command(); } } private static void SwitchWithIntTest(int testCase) { switch (testCase) { case 0: Sleep(); break; case 1: Sleep(); break; case 2: Sleep(); break; case 3: Sleep(); break; case 4: Sleep(); break; case 5: Sleep(); break; case 6: Sleep(); break; case 7: Sleep(); break; case 8: Sleep(); break; case 9: Sleep(); break; case 10: Sleep(); break; case 11: Sleep(); break; case 12: Sleep(); break; case 13: Sleep(); break; case 14: Sleep(); break; case 15: Sleep(); break; case 16: Sleep(); break; case 17: Sleep(); break; case 18: Sleep(); break; case 19: Sleep(); break; } } private static void DictWithIntTest(int testCase) { Action command; if (dictWithInts.TryGetValue(testCase, out command)) { command(); } } private static void Sleep() { Thread.Sleep(MillisecondsSleep); } } }