Skip to content

Instantly share code, notes, and snippets.

@ArchyInf
Created February 11, 2021 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArchyInf/c40af7fbc0c507721da1c41eda4e0f88 to your computer and use it in GitHub Desktop.
Save ArchyInf/c40af7fbc0c507721da1c41eda4e0f88 to your computer and use it in GitHub Desktop.
LambdaOverhead
using System;
using NUnit.Framework;
using Unity.PerformanceTesting;
[TestFixture]
public class PerfTest
{
[Test, Performance]
public void LambdaOverhead()
{
var iterations = 1_000_000;
Measure.Method(() =>
{
for (var i = 0; i < iterations; i++)
{
using (new SomeScope())
{
}
}
}).SampleGroup("Baseline").Run();
Measure.Method(() =>
{
for (var i = 0; i < iterations; i++)
{
using (new SomeScope())
{
DoStuff();
}
}
}).SampleGroup("No Lambda").Run();
Measure.Method(() =>
{
for (var i = 0; i < iterations; i++)
{
DoInScope(() => DoStuff());
}
}).SampleGroup("Lambda").Run();
Measure.Method(() =>
{
for (var i = 0; i < iterations; i++)
{
DoInScope(() => DoStuffInstance());
}
}).SampleGroup("Closure Shared").Run();
Measure.Method(() =>
{
for (var i = 0; i < iterations; i++)
{
DoInScope(() => DoStuff(i));
}
}).SampleGroup("Closure Unique").Run();
}
static void DoInScope(Action action)
{
using (new SomeScope())
{
DoStuff();
}
}
static void DoStuff()
{
}
static void DoStuff(int i)
{
}
void DoStuffInstance()
{
}
struct SomeScope : IDisposable
{
public void Dispose()
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment