This is a mirror of official site: http://jasper-net.blogspot.com/

Optimize your delegate usage

| Sunday, February 17, 2013
Kudos to David Fowler for spotting this! We had a chat on JabbR and David pointed out something quite odd about delegates which he had discovered while optimizing some code.

Let’s assume that we have the following code that declares a delegate and a method that uses it:

public delegate void TestDelegate();

public void Bar(TestDelegate test)
{
    test();
}

Now consider that you want to run this method and pass a method for it to execute that corresponds with the delegate. The process of running this will be in a loop that runs for 10 000 iterations.

The method we want to run is called Foo and looks like the following:

public void Foo() { }
Everything is set up, so what is it that we need to optimize when calling this 10 000 times? Well we have two different ways of using the method with a delegate.

Option 1
The first option is that we can use an anonymous method to call this method looking like the following:

for (var i = 0; i < 10000; i++)
{
    Bar(() => Foo());
}

If we compile this and open it up in Reflector to see what is generated, there’s also some other stuff generated behind the scenes but this is the important part:

TestDelegate test = null;
for (int i = 0; i < 0x2710; i++)
{
    if (test == null)
    {
        test = () => this.Foo();
    }
    this.Bar(test);
}

Looks good so far, right? Let’s take a look at Option 2 and compare.

Option 2
The second option that we have is just writing the method name to tell it to use this like you can see here:

for (var i = 0; i < 10000; i++)
{
    Bar(Foo);
}

This one is quite common and I’ve seen it used a lot, but what happens behind the scenes here?

If we open this up in Reflector we can see that the following code was generated:

for (int i = 0; i < 0x2710; i++)
{
    this.Bar(new TestDelegate(this.Foo));
}

QR: Inline image 1

Posted via email from Jasper-net

0 comments: