Perfomance thoughts on interception Post 1 of several

Today we were talking about weaving. An interesting thing about weaving is that because it is such a powerful tool we need to be careful with the cost that in can add to common things.

Dictionary Access

Imagine for example that the we add some interception cost on a very used method.
You might have something that performs some dictionary look up lets see.

Our tests will create a dictionary with 500 entries and also generate 10000000 random accesses. We will then measure the overhead introduced.

using System;  
using System.Collections.Generic;  
using System.Diagnostics;

class Program  
{
    static void Main(string[] args)
    {
        var dic = new Dictionary<string, object>();

        for (var i = 0; i < 500; i++)
        {
            dic.Add("a" + i, null);
        }
        var accesos = new string[10000000];
        var rand = new Random();
        for (var j = 0; j < 10000000; j++)
        {
            accesos[j] = "a" + rand.Next(500);
        }
        var st = new Stopwatch();
        st.Start();
        object outVal;
        for (var j = 0; j < 10000000; j++)
        {
            var access = accesos[j];
        }
        st.Stop();
        var setupcost = st.ElapsedMilliseconds;
        Console.WriteLine("Cost of setting up randon key access in ms " + setupcost);
        st.Reset();
        st.Start();
        for (var j = 0; j < 10000000; j++)
        {
            var access = accesos[j];
            if (dic.TryGetValue(access, out outVal))
            {

            }
        }
        st.Stop();
        var cost = st.ElapsedMilliseconds;
        Console.WriteLine("Cost of dictionary access (removing the setup cost) in ms" + (cost - setupcost));
        Console.ReadLine();
    }
}

Debug:
In 10 runs the average added overhead is 688ms
If use direct access instead of tryget is 682
Release:
Average is 660
Average is: 641