Skip to content

Make it possible to omit memory allocation for closures #18

@xzxzxc

Description

@xzxzxc

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions