Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@borakasmer
Last active February 11, 2023 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borakasmer/ad24ddef72b73465f41177abc6136fac to your computer and use it in GitHub Desktop.
Save borakasmer/ad24ddef72b73465f41177abc6136fac to your computer and use it in GitHub Desktop.
DictionaryBenchMarker
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DictionaryBenchMarker
{
internal class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<DictioanryBenchmarker>();
}
}
[MemoryDiagnoser]
public class DictioanryBenchmarker
{
[Benchmark]
public List<int> BenchToListTuple()
{
List<(string key, int value)> list = new List<(string, int)>();
for (int i = 1; i < 20000; i++)
{
list.Add(($"{i}_Bora", 5345 + i));
list.Add(($"{i}_Mehmet", 6666 + i));
}
Random random = new Random();
List<int> customerIDList = new List<int>();
for (int i2 = 0; i2 < 100; i2++)
{
int randomNumber = random.Next(0, 20000);
var item = list.FirstOrDefault(item => item.key == $"{randomNumber}_Bora");
var item2 = list.FirstOrDefault(item => item.key == $"{randomNumber}_Mehmet");
customerIDList.Add(item.value);
customerIDList.Add(item2.value);
}
return customerIDList;
}
[Benchmark]
public List<int> BenchToDictioanry()
{
Dictionary<string, int> list = new Dictionary<string, int>();
for (int i = 1; i < 20000; i++)
{
list.Add($"{i}_Bora", 5345 + i);
list.Add($"{i}_Mehmet", 6666 + i);
}
Random random = new Random();
List<int> customerIDList = new List<int>();
for (int i2 = 0; i2 < 100; i2++)
{
int randomNumber = random.Next(0, 20000);
var item = list.Any(x => x.Key.Equals($"{randomNumber}_Bora")) ? list[$"{randomNumber}_Bora"] : 0;
var item2 = list.Any(x => x.Key.Equals($"{randomNumber}_Mehmet")) ? list[$"{randomNumber}_Mehmet"] : 0;
customerIDList.Add(item);
customerIDList.Add(item2);
}
return customerIDList;
}
[Benchmark]
public List<int> BenchToDictioanryTryGetvalue()
{
Dictionary<string, int> list = new Dictionary<string, int>();
for (int i = 1; i < 20000; i++)
{
list.Add($"{i}_Bora", 5345 + i);
list.Add($"{i}_Mehmet", 6666 + i);
}
Random random = new Random();
List<int> customerIDList = new List<int>();
for (int i2 = 0; i2 < 100; i2++)
{
int randomNumber = random.Next(0, 20000);
var item = list.TryGetValue($"{randomNumber}_Bora", out int value);
var item2 = list.TryGetValue($"{randomNumber}_Mehmet", out int value2);
customerIDList.Add(item ? value : 0);
customerIDList.Add(item2 ? value2 : 0);
}
return customerIDList;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment