eShop icon indicating copy to clipboard operation
eShop copied to clipboard

refactor: avoid closure creation

Open Ted-Zhang opened this issue 1 year ago • 3 comments

refactor: avoid closure creation

The ExecutionStrategyExtensions.ExecuteAsync has an overload method to support passing the state, thereby updating the usage to avoid creating the closure to capture the reference.

Since this code example is part of the official documentation, so I think providing a refined code example would be beneficial. Official document link

Ted-Zhang avatar Mar 10 '24 09:03 Ted-Zhang

@dotnet-policy-service agree

Ted-Zhang avatar Mar 10 '24 09:03 Ted-Zhang

The closures capture other variables so I don't think you're really saving anything here. You can check to see if the closure is avoided by making the delegate static.

int i;
F(static func()
{
    Console.WriteLine(i); // compiler error, i is captured but delegate is static
});

void F(Action a);

BrennanConroy avatar May 17 '24 23:05 BrennanConroy

The IExecutionStrategy from EF Core has an overloaded method that allows passing the status, this is leveraging that to avoid the closure creation to capture those variables. https://github.com/dotnet/efcore/blob/fa093d46c94d490317ee87ac257ed5f37a3f5565/src/EFCore/Storage/ExecutionStrategyExtensions.cs#L228C1-L242C1

Ted-Zhang avatar May 19 '24 01:05 Ted-Zhang