C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The comparison here would be invalid if you were changing the value. It would not apply.
Info: The program found that calling ContainsKey on a key that exists is faster here than storing a value in the Dictionary.
ContainsKeySo: If a key is very likely to already exist in the Dictionary, it is best to leave it alone and not reset it.
C# program that benchmarks Dictionary
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
var dict = new Dictionary<string, bool>(StringComparer.Ordinal);
SetTrue1(dict, "test");
SetTrue2(dict, "test");
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
SetTrue1(dict, "test");
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
SetTrue2(dict, "test");
}
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"));
Console.Read();
}
static void SetTrue1(Dictionary<string, bool> dict, string key)
{
dict[key] = true;
}
static void SetTrue2(Dictionary<string, bool> dict, string key)
{
if (!dict.ContainsKey(key))
{
dict[key] = true;
}
}
}
Output
30.81 ns SetTrue1
29.05 ns SetTrue2
Also: You could use TryGetValue and test to see if the value you want to add is also the same as the one that exists.
TryGetValue