using System.Collections.Generic;
using System.Diagnostics;
public static class DictionaryExtensions
public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
throw new ArgumentNullException(nameof(dictionary));
if (!dictionary.ContainsKey(key))
dictionary.Add(key, value);
public static bool TryAddViaException<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
throw new ArgumentNullException(nameof(dictionary));
dictionary.Add(key, value);
catch (ArgumentException)
public static void Main()
Measure((d, k, v) => d.TryAdd(k, v), "TryAdd");
Measure((d, k, v) => d.TryAddViaException(k, v), "TryAddViaException");
private static void Measure(Func<IDictionary<string, int>, string, int, bool> f, string name)
var dictionary = new Dictionary<string, int>();
for (var i = 0; i < 50_000; i += 1)
dictionary.Add(i.ToString(), i);
var stopwatch = new Stopwatch();
for (var i = 25_000; i < 75_000; i += 1)
f(dictionary, i.ToString(), i);
Console.WriteLine($"{name}: {stopwatch.Elapsed}");