I understand that it is handy to create a method on the fly, using lambda, if you only need to call it once but do I gain any perfomance by doing so?
Delegates (such as instances of Action<T>
) are one level of indirection (very similar to virtual method dispatch); the runtime does not just execute the code inside the method when you invoke the delegate; the runtime will first have to figure out what method they reference, then invoke that method.
Delegates certainly don't speed things up. But then you should state what we are comparing them against.
That being said, the minute overhead of delegate dispatch is generally negligible in all but the most extreme scenarios; don't worry too much about the performance of delegate invocation.
Action<int> square = number =>
{
number += 10;
Console.WriteLine(number * number);
};
Can anyone give me a good example/situation when to use this expression?
I would not mutate arguments if I could just as well write the code another way; all the more so when we are talking about a lambda's parameter. I would instead put the value derived from the argument into a (temporary) local variable:
Action<int> square = number =>
{
int n = number + 10;
Console.WriteLine(n * n);
};
The code is not really any longer, and generally easier to understand because you don't have to worry about your lambda accidentally changing an object passed to it.