|
| 1 | +using CacheTable; |
| 2 | +using System; |
| 3 | +using BenchmarkDotNet.Attributes; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Collections.Concurrent; |
| 6 | + |
| 7 | +namespace Benchmark |
| 8 | +{ |
| 9 | + [CoreJob] |
| 10 | + [RPlotExporter, RankColumn] |
| 11 | + public class GuidKeysReadFullTable |
| 12 | + { |
| 13 | + private readonly CacheTable<WrappedString, int> cacheTable = new CacheTable<WrappedString, int>(10, 4); |
| 14 | + private readonly Dictionary<WrappedString, int> dictionary = new Dictionary<WrappedString, int>(); |
| 15 | + private WrappedString[] keys; |
| 16 | + |
| 17 | + struct WrappedString : IEquatable<WrappedString> |
| 18 | + { |
| 19 | + public string Value; |
| 20 | + |
| 21 | + public bool Equals(WrappedString other) => this.Value.Equals(other.Value); |
| 22 | + |
| 23 | + public override int GetHashCode() => this.Value.GetHashCode(); |
| 24 | + |
| 25 | + public override bool Equals(object obj) => this.Equals((WrappedString)obj); |
| 26 | + |
| 27 | + public static implicit operator WrappedString(string str) => new WrappedString { Value = str }; |
| 28 | + } |
| 29 | + |
| 30 | + [GlobalSetup] |
| 31 | + public void Setup() |
| 32 | + { |
| 33 | + while (cacheTable.Count != 40) |
| 34 | + { |
| 35 | + this.cacheTable[Guid.NewGuid().ToString()] = 42; |
| 36 | + } |
| 37 | + |
| 38 | + this.keys = new WrappedString[40]; |
| 39 | + int i = 0; |
| 40 | + foreach (KeyValuePair<WrappedString, int> kvp in cacheTable) |
| 41 | + { |
| 42 | + this.dictionary[kvp.Key] = kvp.Value; |
| 43 | + this.keys[i++] = kvp.Key; |
| 44 | + } |
| 45 | + |
| 46 | + Random rng = new Random(); |
| 47 | + Shuffle(rng, this.keys); |
| 48 | + } |
| 49 | + |
| 50 | + public static void Shuffle<T>(Random rng, T[] array) |
| 51 | + { |
| 52 | + int n = array.Length; |
| 53 | + while (n > 1) |
| 54 | + { |
| 55 | + int k = rng.Next(n--); |
| 56 | + T temp = array[n]; |
| 57 | + array[n] = array[k]; |
| 58 | + array[k] = temp; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + [Benchmark] |
| 63 | + public int CacheTable() |
| 64 | + { |
| 65 | + int sum = 0; |
| 66 | + foreach (var k in this.keys) |
| 67 | + { |
| 68 | + sum += this.cacheTable[k]; |
| 69 | + } |
| 70 | + |
| 71 | + return sum; |
| 72 | + } |
| 73 | + |
| 74 | + [Benchmark(Baseline = true)] |
| 75 | + public int Dictionary() |
| 76 | + { |
| 77 | + int sum = 0; |
| 78 | + foreach (var k in this.keys) |
| 79 | + { |
| 80 | + sum += this.dictionary[k]; |
| 81 | + } |
| 82 | + |
| 83 | + return sum; |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments