Skip to content

Instantly share code, notes, and snippets.

@rflechner
Created May 26, 2016 13:50
Show Gist options
  • Save rflechner/2a3b009841a7dcbd114d857f037dfbdb to your computer and use it in GitHub Desktop.
Save rflechner/2a3b009841a7dcbd114d857f037dfbdb to your computer and use it in GitHub Desktop.
Benchmark C# collections
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var nums1 = Enumerable.Range(1, 1000).ToList();
var nums2 = Enumerable.Range(2000, 5000).ToList();
nums2.Add(50);
var iterations = 10000;
Benchmark(nums1, nums2, iterations, Intersect1, "Double iteration");
Benchmark(nums1, nums2, iterations, Intersect3, "HashSet");
Benchmark(nums1, nums2, iterations, Intersect2, "Dictionary");
Console.WriteLine("Press any key ...");
Console.ReadKey(true);
}
private static void Benchmark(List<int> nums1, List<int> nums2, int iterations, Func<List<int>, List<int>, int?> action, string name)
{
Console.WriteLine("Executing: {0}", name);
var watch = Stopwatch.StartNew();
var v = action(nums1, nums2);
for (var i = 0; i < iterations; i++)
{
action(nums1, nums2);
}
watch.Stop();
Console.WriteLine("result: {0}", v);
Console.WriteLine("elapsed time: {0}", watch.ElapsedMilliseconds);
}
static int? Intersect3(List<int> nums1, List<int> nums2)
{
var hashSet = new HashSet<int>(nums1);
foreach (var i in nums2)
{
if (hashSet.Contains(i))
return i;
}
return null;
}
static int? Intersect2(List<int> nums1, List<int> nums2)
{
var dictionary = nums1.ToDictionary(i => i);
foreach (var i in nums2)
{
if (dictionary.ContainsKey(i))
return i;
}
return null;
}
static int? Intersect1(List<int> nums1, List<int> nums2)
{
for (int i = 0; i < nums1.Count; i++)
{
var n = nums1[i];
for (int j = 0; j < nums2.Count; j++)
{
var m = nums2[j];
if (n == m)
return n;
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment