Search code examples
c#expression-trees

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


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

Solution

  • 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.