Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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