Skip to content

Instantly share code, notes, and snippets.

@mattwarren
Created May 29, 2016 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattwarren/480848b4eafb5843602eedd510d9e1ae to your computer and use it in GitHub Desktop.
Save mattwarren/480848b4eafb5843602eedd510d9e1ae to your computer and use it in GitHub Desktop.
See https://twitter.com/dotMorten/status/736939376282763264 - Point #2 "Do not use Lambdas, as they cause allocations"
[Config(typeof(Config))]
public class Program
{
// To run this code, you need the following NuGet packages:
// - BenchmarkDotNet - version=0.9.6
// - BenchmarkDotNet.Diagnostics.Windows - version=0.9.6
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<Program>();
}
private class Config : ManualConfig
{
public Config()
{
Add(Job.Clr.WithLaunchCount(1));
Add(new MemoryDiagnoser());
Add(JitOptimizationsValidator.FailOnError);
}
}
[Benchmark(Baseline = true)]
public bool Normal()
{
return Tester.Normal("via regular static function call");
}
[Benchmark]
public bool Lambda()
{
// The C# compiler is smart enough to cache the lambda/delegate in a static field, so only allocated once
return Tester.Lambda(() => "via lambda");
}
private string data = "via lambda (that has a \"capture\")";
[Benchmark]
public bool LambdaWithCapture()
{
return Tester.Lambda(() => data);
}
public static class Tester
{
public static bool Normal(string error)
{
return false;
}
public static bool Lambda(Func<string> getData)
{
getData();
return true;
}
}
}
@mattwarren
Copy link
Author

image

@mattwarren
Copy link
Author

mattwarren commented May 29, 2016

BenchmarkDotNet=v0.9.7.0
OS=Microsoft Windows NT 6.1.7601 Service Pack 1
Processor=Intel(R) Core(TM) i7-4800MQ CPU 2.70GHz, ProcessorCount=8
Frequency=2630810 ticks, Resolution=380.1111 ns, Timer=TSC
HostCLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
JitModules=clrjit-v4.6.1076.0

Type=Program  Mode=Throughput  Runtime=Clr  
LaunchCount=1  
Method Median StdDev Gen 0 Gen 1 Gen 2 Bytes Allocated/Op
Normal 0.0535 ns 0.0810 ns - - - 0.00
Lambda 3.3901 ns 0.1060 ns - - - 0.00
LambdaWithCapture 7.9040 ns 0.4950 ns 11,930.00 - - 14.80

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