Skip to content

Instantly share code, notes, and snippets.

@brantburnett
Created September 28, 2021 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brantburnett/25ffd08204b2eaa37c507283bcf580f8 to your computer and use it in GitHub Desktop.
Save brantburnett/25ffd08204b2eaa37c507283bcf580f8 to your computer and use it in GitHub Desktop.
Dictionary Comparison for InFlightOperationSet assuming no lock contention
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
namespace Couchbase.LoadTests
{
public class StatesInFlight
{
private readonly Dictionary<uint, object> _dictionary = new Dictionary<uint, object>();
private readonly ConcurrentDictionary<uint, object> _concurrentDictionary =
new ConcurrentDictionary<uint, object>();
private readonly ConcurrentDictionary<uint, object> _concurrentDictionaryLimited =
new ConcurrentDictionary<uint, object>(2, 16);
private readonly object _obj = new object();
private uint _i = 0;
[Benchmark(Baseline = true)]
public object ConcurrentDict()
{
var i = _i++;
_concurrentDictionary.TryAdd(i, _obj);
_concurrentDictionary.TryRemove(i, out var obj);
return obj;
}
/[Benchmark]
public object Dictionary()
{
var i = _i++;
lock (_obj)
{
_dictionary[i] =_obj;
}
lock (_obj)
{
#if NETCOREAPP
_dictionary.Remove(i, out var obj);
return obj;
#else
if (_dictionary.TryGetValue(i, out var obj))
{
_dictionary.Remove(i);
return obj;
}
else
{
return null;
}
#endif
}
}
}
}
        Method        Job       Runtime    Toolchain     Mean     Error   StdDev Ratio RatioSD Rank
ConcurrentDict Job-NUSUKQ    .NET 4.6.1       net461 96.05 ns 71.593 ns 3.924 ns  1.15    0.03    5
    Dictionary Job-NUSUKQ    .NET 4.6.1       net461 63.69 ns 97.467 ns 5.343 ns  0.76    0.05    3
ConcurrentDict Job-FGGJBC .NET Core 2.1 netcoreapp21 82.43 ns  7.113 ns 0.390 ns  0.99    0.01    4
    Dictionary Job-FGGJBC .NET Core 2.1 netcoreapp21 58.66 ns 95.663 ns 5.244 ns  0.70    0.05    2
ConcurrentDict Job-GFJGKJ .NET Core 3.1 netcoreapp31 83.26 ns 27.953 ns 1.532 ns  1.00    0.00    4
    Dictionary Job-GFJGKJ .NET Core 3.1 netcoreapp31 44.87 ns 10.588 ns 0.580 ns  0.54    0.01    1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment