Skip to content

Instantly share code, notes, and snippets.

@nonnb
Created October 14, 2014 17:25
Show Gist options
  • Save nonnb/9fe9d3cd1f64e2cb5ee0 to your computer and use it in GitHub Desktop.
Save nonnb/9fe9d3cd1f64e2cb5ee0 to your computer and use it in GitHub Desktop.
OM Dictionary vs Switch Function
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject1
{
public enum SomeStatusModeType
{
Status1,
Status2
}
[TestClass]
public class SomeUnitTest
{
public const int NumIterations = 10000000;
public static class AnotherStatusModeType
{
public const int AnotherStatus1 = 1;
public const int AnotherStatus2 = 2;
public const int AnotherStatus3 = 3;
public const int AnotherStatus4 = 4;
}
public static int[] ReferralStatusModes(SomeStatusModeType modeType)
{
switch (modeType)
{
case SomeStatusModeType.Status1:
return new[]
{
AnotherStatusModeType.AnotherStatus1,
AnotherStatusModeType.AnotherStatus2,
AnotherStatusModeType.AnotherStatus3,
};
case SomeStatusModeType.Status2:
return new[]
{
AnotherStatusModeType.AnotherStatus3,
AnotherStatusModeType.AnotherStatus4
};
default:
return new int[] { };
}
}
private readonly static IDictionary<SomeStatusModeType, int[]> ReferralStatusModesDictionary = new Dictionary<SomeStatusModeType, int[]>
{
{
SomeStatusModeType.Status1,
new[]
{
AnotherStatusModeType.AnotherStatus1,
AnotherStatusModeType.AnotherStatus2,
AnotherStatusModeType.AnotherStatus3,
}
},
{
SomeStatusModeType.Status2,
new[]
{
AnotherStatusModeType.AnotherStatus3,
AnotherStatusModeType.AnotherStatus4
}
}
};
private void Time(string subject, Action actionToTime)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
try
{
actionToTime.Invoke();
}
finally
{
sw.Stop();
System.Diagnostics.Debug.WriteLine("{0} - elapsed ms: {1}", subject, sw.ElapsedMilliseconds);
}
}
[TestMethod]
public void DemonstrateEvaluationOfFunction()
{
Time("Switch Function", () =>
{
var theVal = Enumerable.Range(0, NumIterations)
.Select(_ => SomeUnitTest.ReferralStatusModes(SomeStatusModeType.Status1).Contains(_));
theVal.ToList();
});
}
[TestMethod]
public void DemonstrateDictionary()
{
Time("Dictionary", () =>
{
var theVal = Enumerable.Range(0, NumIterations)
.Select(_ => ReferralStatusModesDictionary[SomeStatusModeType.Status1].Contains(_));
theVal.ToList();
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment