Why compiler didn't use same object reference for a static expression tree?

c# expression-trees

Question

As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

To clarify the question please see the example:

static void Main(string[] args)
{
    Test(p => true);//2637164
    Test(p => true);//3888474
    Test("true");//-292522067
    Test("true");//-292522067
    Console.ReadKey();
}

public static void Test(Expression<Func<string,bool>> exp)
{
    Console.WriteLine(exp.GetHashCode());
}

public static void Test(string str)
{
    Console.WriteLine(str.GetHashCode());
}
1
4
11/13/2017 6:30:23 AM

Accepted Answer

As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

The spec says that the compiler is permitted but not required to intern identical lambdas.

String literals are interned by the runtime for free; there's no cost to the compiler developer to do it.

The reason why I didn't intern expression trees is because every day we spent working on pointless unnecessary "optimizations" for unrealistic scenarios that actually save no valuable resource is a day that Visual Studio would have slipped its schedule. We spent that time on actual optimizations.

8
11/13/2017 6:46:38 AM

Popular Answer

Blindly guessing of what your actual issue is: instead of reference equality, use the answer from this question as the IEqualityComparer for your dictionary. It is obviously not as fast as Object.ReferenceEquals, but is definately faster than compiling the expression tree I would imagine.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow