[SimpleJob(RuntimeMoniker.Net80)]
[MemoryDiagnoser]
public class Benchmark
{
private IDictionary<string, string> items = new Dictionary<string, string>
{
["1"] = "A"
};
private string clientListKey = "1";
[Benchmark]
public void ContainsKey_Indexer()
{
if (items.ContainsKey(clientListKey) == true)
{
var value = items[clientListKey];
}
}
[Benchmark]
public void TryGetValue()
{
if (items.TryGetValue(clientListKey, out var value) == true)
{
}
}
}
void Main() => BenchmarkRunner.Run<Benchmark>();
// * Summary *
BenchmarkDotNet v0.14.0, Windows 10 (10.0.19045.4780/22H2/2022Update)
Intel Core i7-10700 CPU 2.90GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK 8.0.401
[Host] : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2
Job=.NET 8.0 Runtime=.NET 8.0
| Method | Mean | Error | StdDev | Allocated |
|-------------------- |---------:|---------:|---------:|----------:|
| ContainsKey_Indexer | 19.34 ns | 0.226 ns | 0.200 ns | - |
| TryGetValue | 10.46 ns | 0.171 ns | 0.142 ns | - |
// * Hints *
Outliers
Benchmark.ContainsKey_Indexer: .NET 8.0 -> 1 outlier was removed (21.41 ns)
Benchmark.TryGetValue: .NET 8.0 -> 2 outliers were removed (12.39 ns, 13.60 ns)
// * Legends *
Mean : Arithmetic mean of all measurements
Error : Half of 99.9% confidence interval
StdDev : Standard deviation of all measurements
Allocated : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)
1 ns : 1 Nanosecond (0.000000001 sec)
Use Append method instead of ToList and Add methods.
Use TryGetValue method instead of ContainsKey method and Indexer (CA1854).