This benchmark compares the TryGetValue method against ContainsKey and indexer. It compares 1 lookup against 2 lookups.
using System;
using System.Collections.Generic;
using System.Diagnostics;
const int _max = 10000000;
var test = new Dictionary<string, int>();
test[
"key"] = 1;
int sum = 0;
// Version 1: use ContainsKey and access the key again for its value.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (test.ContainsKey(
"key"))
{
sum += test[
"key"];
}
}
s1.Stop();
// Version 2: use TryGetValue and use the key already accessed.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (test.TryGetValue(
"key", out int result))
{
sum += result;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
38.11 ns ContainsKey, indexer
21.16 ns TryGetValue