Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using BenchmarkDotNet.Attributes;
- using BenchmarkDotNet.Jobs;
- using BenchmarkDotNet.Running;
- public static class Program
- {
- public static void Main() => BenchmarkRunner.Run<Benches>();
- }
- [SimpleJob(RuntimeMoniker.Net48)]
- [SimpleJob(RuntimeMoniker.Net60)]
- public class Benches
- {
- [Params(50_000)]
- public int InitialSeed { get; set; }
- [Params(25_000, 49_500, 49_950, 49_999, 50_000)]
- public int BenchmarkStart { get; set; }
- [Params(50_000)]
- public int BenchmarkSize { get; set; }
- private Dictionary<string, int> _dictionary = new Dictionary<string, int>();
- [IterationSetup]
- public void Seed()
- {
- _dictionary = new Dictionary<string, int>();
- for (var i = 0; i < InitialSeed; i += 1)
- {
- _dictionary.Add(i.ToString(), i);
- }
- }
- [Benchmark(Baseline = true)]
- public void TryAdd()
- {
- for (var i = BenchmarkStart; i < BenchmarkStart + BenchmarkSize; i += 1)
- {
- _dictionary.TryAdd(i.ToString(), i);
- }
- }
- [Benchmark]
- public void TryAddViaException()
- {
- for (var i = BenchmarkStart; i < BenchmarkStart + BenchmarkSize; i += 1)
- {
- _dictionary.TryAddViaException(i.ToString(), i);
- }
- }
- }
- public static class DictionaryExtensions
- {
- public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException(nameof(dictionary));
- }
- if (!dictionary.ContainsKey(key))
- {
- dictionary.Add(key, value);
- return true;
- }
- return false;
- }
- public static bool TryAddViaException<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException(nameof(dictionary));
- }
- try
- {
- dictionary.Add(key, value);
- return true;
- }
- catch (ArgumentException)
- {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement