Skip to content

Instantly share code, notes, and snippets.

@gyuwon
Created February 16, 2016 02:54
Show Gist options
  • Save gyuwon/d5191e0e8d0cd8c80922 to your computer and use it in GitHub Desktop.
Save gyuwon/d5191e0e8d0cd8c80922 to your computer and use it in GitHub Desktop.
Method call performance
using System;
using System.Diagnostics;
using System.Reflection;
namespace CallPerf
{
internal interface ICounter
{
long Count { get; }
void Increase();
}
internal delegate void Increase();
internal class Counter : ICounter
{
private long _count;
public long Count => _count;
public void Increase() => _count++;
}
public class Program
{
public static void Main()
{
int n = 1000 * 1000 * 1000;
Direct(n);
Console.WriteLine();
Delegate(n);
//Console.WriteLine();
//Reflection(n);
Console.WriteLine();
CreateDelegate(n);
}
private static void Direct(int n)
{
using (Job.StartNew("Direct"))
{
Counter counter = new Counter();
for (int i = 0; i < n; i++)
counter.Increase();
Console.WriteLine("Count: {0}", counter.Count);
}
}
private static void Delegate(int n)
{
using (Job.StartNew("Delegate"))
{
Counter counter = new Counter();
Increase increase = counter.Increase;
for (int i = 0; i < n; i++)
increase();
Console.WriteLine("Count: {0}", counter.Count);
}
}
private static void Reflection(int n)
{
using (Job.StartNew("Reflection"))
{
Counter counter = new Counter();
MethodInfo m = typeof(Counter).GetMethod("Increase", BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < n; i++)
m.Invoke(counter, null);
Console.WriteLine("Count: {0}", counter.Count);
}
}
private static void CreateDelegate(int n)
{
using (Job.StartNew("CreateDelegate"))
{
Counter counter = new Counter();
MethodInfo m = typeof(Counter).GetMethod("Increase", BindingFlags.Public | BindingFlags.Instance);
Increase increase = (Increase)System.Delegate.CreateDelegate(typeof(Increase), counter, m);
for (int i = 0; i < n; i++)
increase();
Console.WriteLine("Count: {0}", counter.Count);
}
}
}
internal class Job : IDisposable
{
public static Job StartNew(string name)
{
return new Job(name);
}
private string _name;
private Stopwatch _stopwatch;
private Job(string name)
{
this._name = name;
this._stopwatch = Stopwatch.StartNew();
Console.WriteLine("[{0} started]", this._name);
}
public void Dispose()
{
this._stopwatch.Stop();
Console.WriteLine("[{0} finished] {1}ms elapsed", this._name, this._stopwatch.ElapsedMilliseconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment