|
| 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 SetSingleString |
| 12 | + { |
| 13 | + private static readonly WrappedString Zero = "0"; |
| 14 | + |
| 15 | + private readonly CacheTable<WrappedString, int> cacheTable = new CacheTable<WrappedString, int>(10, 4); |
| 16 | + private readonly ConcurrentCacheTable<WrappedString, int> concurrentCacheTable = new ConcurrentCacheTable<WrappedString, int>(10, 4, Environment.ProcessorCount); |
| 17 | + private readonly Dictionary<WrappedString, int> dictionary = new Dictionary<WrappedString, int>(); |
| 18 | + private readonly ConcurrentDictionary<WrappedString, int> concurrentDictionary = new ConcurrentDictionary<WrappedString, int>(); |
| 19 | + |
| 20 | + // Wrap the string because Dictionary has special code to optimize |
| 21 | + // string hashing. This levels the playing field. |
| 22 | + struct WrappedString : IEquatable<WrappedString> |
| 23 | + { |
| 24 | + public string Value; |
| 25 | + |
| 26 | + public bool Equals(WrappedString other) => this.Value.Equals(other.Value); |
| 27 | + |
| 28 | + public override int GetHashCode() => this.Value.GetHashCode(); |
| 29 | + |
| 30 | + public override bool Equals(object obj) => this.Equals((WrappedString)obj); |
| 31 | + |
| 32 | + public static implicit operator WrappedString(string str) => new WrappedString { Value = str }; |
| 33 | + } |
| 34 | + |
| 35 | + [Benchmark] |
| 36 | + public void CacheTable() |
| 37 | + { |
| 38 | + this.cacheTable[Zero] = 0; |
| 39 | + } |
| 40 | + |
| 41 | + [Benchmark] |
| 42 | + public void ConcurrentCacheTable() |
| 43 | + { |
| 44 | + this.concurrentCacheTable[Zero] = 0; |
| 45 | + } |
| 46 | + |
| 47 | + [Benchmark] |
| 48 | + public void Dictionary() |
| 49 | + { |
| 50 | + this.dictionary[Zero] = 0; |
| 51 | + } |
| 52 | + |
| 53 | + [Benchmark] |
| 54 | + public void ConcurrentDictionary() |
| 55 | + { |
| 56 | + this.concurrentDictionary[Zero] = 0; |
| 57 | + } |
| 58 | + |
| 59 | + [Benchmark(Baseline = true)] |
| 60 | + public int Hash() |
| 61 | + { |
| 62 | + return Zero.GetHashCode(); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments