Are there any benefits to using a C# method group if available?

前端 未结 7 1134
孤街浪徒
孤街浪徒 2020-12-03 10:55

When dealing with something like a List you can write the following:

list.ForEach(x => Console.WriteLine(x));

7条回答
  •  猫巷女王i
    2020-12-03 11:31

    There is an extra level of indirection when using the lambda expression. With a non-closure expression like that, you'll simply have an extra method call in-between, as mentioned by others.

    There are a few interesting differences though. In the second case, a new delegate instance is being created on each call. For the former, the delegate is created once and cached as a hidden field, so if you're calling a lot you'll save on allocations.

    Additionally, if you introduce a local variable into the lambda expression, it becomes a closure and instead of just a local method being generated, a new class will be created to hold this information, meaning an extra allocation there.

提交回复
热议问题