Skip to content

Instantly share code, notes, and snippets.

@mellinoe
Created October 21, 2017 05:25
Show Gist options
  • Save mellinoe/a867c982c3037896d72772862c414c67 to your computer and use it in GitHub Desktop.
Save mellinoe/a867c982c3037896d72772862c414c67 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class Program
{
private static readonly Dictionary<int, Func<int, int>> _funcs = new Dictionary<int, Func<int, int>>();
static void Main(string[] args)
{
for (int iter = 0; iter < 1000000; iter++)
{
for (int i = 1; i < 5; i++)
{
Func<int, int> func = GetFunc(i);
}
}
}
static Func<int, int> GetFunc(int i)
{
if (!_funcs.TryGetValue(i, out var ret))
{
// This causes no allocations
ret = CreateFunc(i);
// This causes mass allocations
// ret = val => i + 1;
_funcs.Add(i, ret);
}
return ret;
}
static Func<int, int> CreateFunc(int i)
{
return val => i + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment