Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a lambda create a new instance everytime it is invoked?

I'm curious to know whether a Lambda (when used as delegate) will create a new instance every time it is invoked, or whether the compiler will figure out a way to instantiate the delegate only once and pass in that instance.

More specifically, I'm wanting to create an API for an XNA game that I can use a lambda to pass in a custom call back. Since this will be called in the Update method (which is called many times per second) it would be pretty bad if it newed up an instance everytime to pass in the delegate.

InputManager.GamePads.ButtonPressed(Buttons.A, s => s.MoveToScreen<NextScreen>());
like image 819
Joel Martinez Avatar asked Jul 16 '09 02:07

Joel Martinez


1 Answers

Yes, it will cache them when it can:

using System;

class Program {
    static void Main(string[] args) {
        var i1 = test(10);
        var i2 = test(20);
        System.Console.WriteLine(object.ReferenceEquals(i1, i2));
    }

    static Func<int, int> test(int x) {
        Func<int, int> inc = y => y + 1;
        Console.WriteLine(inc(x));
        return inc;
    }
}

It creates a static field, and if it's null, populates it with a new delegate, otherwise returns the existing delegate.

Outputs 10, 20, true.

like image 143
MichaelGG Avatar answered Oct 27 '22 10:10

MichaelGG