Skip to content

Instantly share code, notes, and snippets.

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 daryllabar/21614ddfb85d6578223a6d861fb5327b to your computer and use it in GitHub Desktop.
Save daryllabar/21614ddfb85d6578223a6d861fb5327b to your computer and use it in GitHub Desktop.
Test to determine if there is a performance impact calling a method passed as an Action instead of directly. To be run in LinqPad (as a C# Program)
void Main()
{
RunDirectly();
RunIndirectly();
var runs = 1000000;
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunDirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{runs} Direct Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunIndirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine($"{runs} Indirect Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunIndirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine($"{runs} Indirect Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunDirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{runs} Direct Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunDirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{runs} Direct Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunIndirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine($"{runs} Indirect Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunIndirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine($"{runs} Indirect Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
for (int i = 0; i < runs; i++)
{
RunDirectly();
}
sw.Stop();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{runs} Direct Executions: {sw.ElapsedMilliseconds}");
sw.Reset();
}
int count = 0;
private void RunDirectly()
{
count++;
}
private void RunIndirectly()
{
Action m = () => { count++; };
m();
}
@daryllabar
Copy link
Author

I'm getting this as an example:

1000000 Direct Executions: 6
1000000 Indirect Executions: 24
1000000 Indirect Executions: 27
1000000 Direct Executions: 5
1000000 Direct Executions: 5
1000000 Indirect Executions: 30
1000000 Indirect Executions: 26
1000000 Direct Executions: 3

About 3-5 time slower or 20ish ms / 1,000,000, or .00002 ms per call. I think I can handle that ;)

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