Skip to content

Instantly share code, notes, and snippets.

@rickyah
Created April 4, 2014 12:44
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 rickyah/9973971 to your computer and use it in GitHub Desktop.
Save rickyah/9973971 to your computer and use it in GitHub Desktop.
Benchmark c# accessors vs member variables
using System;
using System.Diagnostics;
public class TestClass
{
public int member;
public int property {get; set;}
}
public static class EntryPoint
{
public static void Main(string[] args)
{
int iterations = 100000000;
int testValue;
TestClass testClass;
if (args.Length == 1)
{
try
{
iterations = int.Parse(args[0]);
}catch{}
}
testClass = new TestClass();
Profile("set member value "+ iterations +" times", iterations, () =>
{
testClass.member = 42;
});
testClass = new TestClass();
testClass.member = 42;
Profile("get member value "+ iterations +" times", iterations, () =>
{
testValue = testClass.member;
});
testClass = new TestClass();
Profile("set property value "+ iterations +" times", iterations, () =>
{
testClass.property = 42;
});
testClass = new TestClass();
testClass.member = 42;
Profile("get property value "+ iterations +" times", iterations, () =>
{
testValue = testClass.property;
});
}
static void Profile(string description, int iterations, Action func)
{
// clean up
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// warm up
func();
var watch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++) {
func();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment