Problem
Consider the following code
using Cathei.LinqGen;
int[] array = new int[] { 1, 2, 3, 4, 5 };
int upperLimit = 3;
int result = array.Gen()
.Where(x => x < upperLimit) // <- closure, memory allocation
.Sum();
A new instance of a compiler-generated class will be created each time this code executes to store closure values (upperLimit in this case). We could omit an allocation if we pass the upperLimit variable to the predicate. For example, GetOrAdd method of a concurrent dictionary has a factoryArgument parameter to achieve the same improvement.
Proposed solution
Add an overload for the Gen method with an argument representing the state needed for delegates. Then, the previous code can be replaced with the
using Cathei.LinqGen;
int[] array = new int[] { 1, 2, 3, 4, 5 };
int upperLimit = 3;
int result = array.Gen(upperLimit)
.Where(static (x, upperLimit) => x < upperLimit) // <- no closure, delegate will be cached
.Sum();
Problem
Consider the following code
A new instance of a compiler-generated class will be created each time this code executes to store closure values (
upperLimitin this case). We could omit an allocation if we pass theupperLimitvariable to the predicate. For example, GetOrAdd method of a concurrent dictionary has afactoryArgumentparameter to achieve the same improvement.Proposed solution
Add an overload for the
Genmethod with an argument representing the state needed for delegates. Then, the previous code can be replaced with the