|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 5 | + |
| 6 | +namespace Asn1Parser.Tests; |
| 7 | +[TestClass] |
| 8 | +public class CollectionPerfTests { |
| 9 | + static readonly List<Byte> _list = [0, 1, 2, 5, 6, 9, 10, 12, 13, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]; |
| 10 | + static readonly HashSet<Byte> _hashSet = [0, 1, 2, 5, 6, 9, 10, 12, 13, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]; |
| 11 | + const Int32 ITERATIONS = 1000000; |
| 12 | + |
| 13 | + [TestMethod] |
| 14 | + public void TestFirstMatch() { |
| 15 | + assertGlobal(0); |
| 16 | + } |
| 17 | + [TestMethod] |
| 18 | + public void TestMiddleMatch() { |
| 19 | + assertGlobal(20); |
| 20 | + } |
| 21 | + [TestMethod] |
| 22 | + public void TestLastMatch() { |
| 23 | + assertGlobal(30); |
| 24 | + } |
| 25 | + [TestMethod] |
| 26 | + public void TestNoMatch() { |
| 27 | + assertGlobal(255); |
| 28 | + } |
| 29 | + |
| 30 | + static void assertGlobal(Byte searchByte) { |
| 31 | + TimeSpan list = executeAction(_list.Contains, searchByte, ITERATIONS); |
| 32 | + TimeSpan hashSet = executeAction(_hashSet.Contains, searchByte, ITERATIONS); |
| 33 | + assertListIsFaster(list, hashSet); |
| 34 | + } |
| 35 | + static void assertListIsFaster(TimeSpan list, TimeSpan hashSet) { |
| 36 | + Assert.IsTrue(list < hashSet); |
| 37 | + } |
| 38 | + //static void assertListIsFaster3xTimes(TimeSpan list, TimeSpan hashSet) { |
| 39 | + // Double ratio = hashSet / list; |
| 40 | + // Console.WriteLine(ratio); |
| 41 | + // Assert.IsTrue(ratio >= 3); |
| 42 | + //} |
| 43 | + static TimeSpan executeAction(Func<Byte, Boolean> action, Byte searchValue, Int32 iterations) { |
| 44 | + var sw = new Stopwatch(); |
| 45 | + sw.Start(); |
| 46 | + for (Int32 i = 0; i < iterations; i++) { |
| 47 | + action.Invoke(searchValue); |
| 48 | + } |
| 49 | + sw.Stop(); |
| 50 | + |
| 51 | + return sw.Elapsed; |
| 52 | + } |
| 53 | +} |
0 commit comments