Skip to content

Instantly share code, notes, and snippets.

@rickyah
Created April 4, 2014 12:44

Revisions

  1. rickyah created this gist Apr 4, 2014.
    76 changes: 76 additions & 0 deletions BenchmarkProperties.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    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);
    }
    }