Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I capture a local variable into a LINQ Expression as a constant rather than a closure reference?

Tags:

c#

lambda

linq

I'd like to say

int x = magic(), y = moremagic();
return i => i + (x/y);

and have the x be captured as a constant instead of a variable reference. The idea is that x will never change and so when the expression is later compiled, the compiler to can do constant folding and produce more efficient code -- i.e. calculating x/y once instead of on every call, via pointer dereferences into a closure record.

There is no way to mark x as readonly within a method, and the compiler is not clever enough to detect that it doesn't change after the creation of the expression.

I'd hate to have to build the expression by hand. Any brilliant ideas?

UPDATE: I ended up using the marvelous LinqKit to build a partial evaluator that will do the substitutions I want. The transform is only safe if you know that relevant references will not change, but it worked for my purposes. It is possible to restrict the partial evaluation only to direct members of your closure, which you control, by adding an extra check or two in there, which is fairly obvious on inspection of the sample code provided in the LinqKit.

/// <summary>Walks your expression and eagerly evaluates property/field members and substitutes them with constants.
/// You must be sure this is semantically correct, by ensuring those fields (e.g. references to captured variables in your closure)
/// will never change, but it allows the expression to be compiled more efficiently by turning constant numbers into true constants, 
/// which the compiler can fold.</summary>
public class PartiallyEvaluateMemberExpressionsVisitor : ExpressionVisitor
{
    protected override Expression VisitMemberAccess(MemberExpression m)
    {
        Expression exp = this.Visit(m.Expression);

        if (exp == null || exp is ConstantExpression) // null=static member
        {
            object @object = exp == null ? null : ((ConstantExpression)exp).Value;
            object value = null; Type type = null;
            if (m.Member is FieldInfo)
            {
                FieldInfo fi = (FieldInfo)m.Member;
                value = fi.GetValue(@object);
                type = fi.FieldType;
            }
            else if (m.Member is PropertyInfo)
            {
                PropertyInfo pi = (PropertyInfo)m.Member;
                if (pi.GetIndexParameters().Length != 0)
                    throw new ArgumentException("cannot eliminate closure references to indexed properties");
                value = pi.GetValue(@object, null);
                type = pi.PropertyType;
            }
            return Expression.Constant(value, type);
        }
        else // otherwise just pass it through
        {
            return Expression.MakeMemberAccess(exp, m.Member);
        }
    }
}
like image 862
Sebastian Good Avatar asked Oct 21 '10 20:10

Sebastian Good


2 Answers

No there is no way to do this in C#. The compiler does not support capturing variables by value / const. Nor can you convert a non-const value into a const value at runtime in this manner.

Additionally the C# compiler only does constant folding during the initial compilation for known constant values. If it was possible to freeze a value at runtime into a constant it wouldn't participate in compiler constant folding because it happens at runtime.

like image 78
JaredPar Avatar answered Nov 14 '22 10:11

JaredPar


The compiler doesn't do this type of "value caching". Constant folding is done at compile time for constants only, not for readonly fields and certainly not for local variables which do not have a known value at compile time.

You have to make this yourself, but it has to stay a closure reference (since the value is in fact not determinable at compile time, which is why it is likely to be put in the closure when the expression is built):

int x = magic(), y = moremagic();
int xy = x/y;
return i => i + xy;
like image 2
Lucero Avatar answered Nov 14 '22 11:11

Lucero