Advertisement
Guest User

TryAddViaException bench

a guest
Apr 25th, 2022
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using BenchmarkDotNet.Attributes;
  4. using BenchmarkDotNet.Jobs;
  5. using BenchmarkDotNet.Running;
  6.  
  7. public static class Program
  8. {
  9.     public static void Main() => BenchmarkRunner.Run<Benches>();
  10. }
  11.  
  12. [SimpleJob(RuntimeMoniker.Net48)]
  13. [SimpleJob(RuntimeMoniker.Net60)]
  14. public class Benches
  15. {
  16.     [Params(50_000)]
  17.     public int InitialSeed { get; set; }
  18.  
  19.     [Params(25_000, 49_500, 49_950, 49_999, 50_000)]
  20.     public int BenchmarkStart { get; set; }
  21.  
  22.     [Params(50_000)]
  23.     public int BenchmarkSize { get; set; }
  24.  
  25.     private Dictionary<string, int> _dictionary = new Dictionary<string, int>();
  26.  
  27.     [IterationSetup]
  28.     public void Seed()
  29.     {
  30.         _dictionary = new Dictionary<string, int>();
  31.         for (var i = 0; i < InitialSeed; i += 1)
  32.         {
  33.             _dictionary.Add(i.ToString(), i);
  34.         }
  35.     }
  36.  
  37.     [Benchmark(Baseline = true)]
  38.     public void TryAdd()
  39.     {
  40.         for (var i = BenchmarkStart; i < BenchmarkStart + BenchmarkSize; i += 1)
  41.         {
  42.             _dictionary.TryAdd(i.ToString(), i);
  43.         }
  44.     }
  45.  
  46.     [Benchmark]
  47.     public void TryAddViaException()
  48.     {
  49.         for (var i = BenchmarkStart; i < BenchmarkStart + BenchmarkSize; i += 1)
  50.         {
  51.             _dictionary.TryAddViaException(i.ToString(), i);
  52.         }
  53.     }
  54. }
  55.  
  56. public static class DictionaryExtensions
  57. {
  58.     public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
  59.     {
  60.         if (dictionary == null)
  61.         {
  62.             throw new ArgumentNullException(nameof(dictionary));
  63.         }
  64.  
  65.         if (!dictionary.ContainsKey(key))
  66.         {
  67.             dictionary.Add(key, value);
  68.             return true;
  69.         }
  70.  
  71.         return false;
  72.     }
  73.  
  74.     public static bool TryAddViaException<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
  75.     {
  76.         if (dictionary == null)
  77.         {
  78.             throw new ArgumentNullException(nameof(dictionary));
  79.         }
  80.  
  81.         try
  82.         {
  83.             dictionary.Add(key, value);
  84.             return true;
  85.         }
  86.         catch (ArgumentException)
  87.         {
  88.             return false;
  89.         }
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement