Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created November 30, 2018 14:29
Show Gist options
  • Save xoofx/6518223015cb904fc1566be16a5c57e9 to your computer and use it in GitHub Desktop.
Save xoofx/6518223015cb904fc1566be16a5c57e9 to your computer and use it in GitHub Desktop.
Interface vs direct calls
// Gist that shows the difference of an interface call
// Two cases in this benchmark:
// - Dictionary that should not inline
// - List that should inline
// We are also using the enumerator to show the impact on allocation as well.
/*
Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
------------------- |----------:|----------:|----------:|------------:|------------:|------------:|--------------------:|
ProcessDictionary | 27.109 ns | 0.1258 ns | 0.1176 ns | - | - | - | - |
ProcessIDictionary | 51.636 ns | 0.3541 ns | 0.3312 ns | 0.0114 | - | - | 48 B |
ProcessList | 1.237 ns | 0.0298 ns | 0.0265 ns | - | - | - | - |
ProcessIList | 24.101 ns | 0.1926 ns | 0.1802 ns | 0.0095 | - | - | 40 B |
*/
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace BenchDictionary
{
[MemoryDiagnoser]
public class Program
{
private static Dictionary<int, int> _values;
private static List<int> _listValues;
static Program()
{
_values= new Dictionary<int, int>();
for (int i = 0; i < 10; i++)
{
_values.Add(i, i);
}
_listValues = new List<int>();
_listValues.Add(0);
_listValues.Add(1);
_listValues.Add(2);
}
[Benchmark]
public static int ProcessDictionary()
{
return _values[0] + _values[1] + _values[2] + _values.GetEnumerator().Current.Key; }
[Benchmark]
public static int ProcessIDictionary()
{
return ((IDictionary<int, int>) _values)[0] + ((IDictionary<int, int>) _values)[1] + ((IDictionary<int, int>) _values)[2] + ((IDictionary<int, int>) _values).GetEnumerator().Current.Key;
}
[Benchmark]
public static int ProcessList()
{
return _listValues[0] + _listValues[1] + _listValues[2] + _listValues.GetEnumerator().Current;
}
[Benchmark]
public static int ProcessIList()
{
return ((IList<int>) _listValues)[0] + ((IList<int>) _listValues)[1] + ((IList<int>) _listValues)[2] + ((IList<int>) _listValues).GetEnumerator().Current;
}
static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment