Created
October 21, 2017 05:25
-
-
Save mellinoe/a867c982c3037896d72772862c414c67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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