Skip to content

Instantly share code, notes, and snippets.

@smoogipoo
Created July 22, 2020 15:15
Show Gist options
  • Select an option

  • Save smoogipoo/810c033962b8a95289dbdabd9d84801b to your computer and use it in GitHub Desktop.

Select an option

Save smoogipoo/810c033962b8a95289dbdabd9d84801b to your computer and use it in GitHub Desktop.
[MemoryDiagnoser]
public class BenchmarkMethodDelegateAllocations
{
private readonly List<int> list = new List<int> { 1, 2, 3 };
private int field = 2;
[Benchmark(Baseline = true)]
public int SafeMethod()
{
int res = 0;
for (int i = 0; i < 1000; i++)
res += safeMethod();
return res;
}
[Benchmark]
public int AllocatingMethod()
{
int res = 0;
for (int i = 0; i < 1000; i++)
res += allocatingMethod();
return res;
}
private int safeMethod()
{
return 0;
int local = 2;
return list.Count(_ => 0 > local);
}
private int allocatingMethod()
{
return 0;
int local = 2;
return list.Count(_ => field > local);
}
}
@smoogipoo
Copy link
Copy Markdown
Author

Method Mean Error StdDev Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
SafeMethod 547.6 ns 1.08 ns 1.01 ns 1.00 0.00 - - - -
AllocatingMethod 8,790.7 ns 209.87 ns 618.80 ns 16.92 0.67 0.9460 - - 32000 B

@smoogipoo
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment