ContainsKey is many times faster than ContainsValue, and this is most apparent in large dictionaries. Consider this benchmark. A dictionary of 1000 key-value pairs is created.
using System;
using System.Collections.Generic;
using System.Diagnostics;
const int _max = 10000;
// Create a lookup table.
var lookup = new Dictionary<string, string>();
for (int i = 0; i < 1000; i++)
{
lookup[i.ToString() +
"a"] = i.ToString() +
"b";
}
// Version 1: use ContainsValue.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (!lookup.ContainsValue(
"999b"))
{
return;
}
}
s1.Stop();
// Version 2: use ContainsKey.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (!lookup.ContainsKey(
"999a"))
{
return;
}
}
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"));
13388.79 ns ContainsValue
37.49 ns ContainsKey