Carl R
Carl R

Reputation: 8214

Can an Expression<Func<T1, T2>> variable be reliably used as key in a dictionary?

I have a function that currently uses a Func<T1, T2> as argument.
I want it to use an Expression<Func<T1, T2>> as argument so that I can traverse the expression tree in certain circumstances.

For every call I want to use the function, so I would need to Compile() the expression. In order to not having to recompile all of the expressions, I would like to put them in a dictionary.

The calls to my method looks like this:

var foo = MyFunc(x => x.Field);

Is the following solution correct with regards to the usage of Expression as a dictionary key?

static Dictionary<Expression<Func<T1, T2>>, Func<T1, T2>> s_functions = new Dictionary<Expression<Func<T1, T2>>, Func<T1, T2>>();

public T2 MyFunc(Expression<Func<T1, T2>> selectorExpression)
{
    if (!s_functions.ContainsKey(selectorExpression))
    {
        s_functions.Add(selectorExpression, selectorExpression.Compile());
    }

    Func<T1, T2> selector = s_functions[selectorExpression];
}

EDIT

What would be a good way to solve it from a performance perspective?

Upvotes: 3

Views: 238

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112602

Use selectorExpression.ToString() as key. It is not perfect since equivalent expressions using different parameter names will yield different strings, but it's a very simple approach.

Test:

Expression<Func<int,int>> expr = x => x * x;
MessageBox.Show(expr.ToString()); // ==> "x => (x * x)"

Upvotes: 2

Jon
Jon

Reputation: 437584

Unfortunately not, but the problem will only manifest as a performance bug.

The issue is that Expression<TDelegate> does not implement IEquatable<Expression<TDelegate>> so the default equality comparer used by the dictionary will only do reference equality. This means that different instances of the same expression will not compare identical, which will lead to cache misses that should have been hits. On the other hand instances of different expressions will always compare different, so there's no logic bug.

You can fix this problem by providing a custom equality comparer for the dictionary, but there's also the small matter of having to write one -- it's going to be a tall order.

On the bright side, it might be possible to write a comparer that has the same performance bug as the original implementation (but reduced in scope) in exchange for convenience -- the reduction in scope might account for all or most the cases you are actually going to encounter! For example, you might want to try comparing based on equality of ToString() representations. As long as the comparer does not produce any false positives there is only room for improvement.

Upvotes: 4

Related Questions