Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
}
like image 608
Reza ArabQaeni Avatar asked Jan 29 '23 05:01

Reza ArabQaeni


1 Answers

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.

like image 200
Eric Lippert Avatar answered Feb 06 '23 11:02

Eric Lippert