Ответ 1
Код С#:
List<string> list = new List<string>();
list.Where(a => a == typeof(String).ToString());
Lambda выражение в MSIL, Конфигурация отладки:
.method private hidebysig static bool '<Main>b__0'(string a) cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 26 (0x1a)
.maxstack 2
.locals init ([0] bool CS$1$0000)
IL_0000: ldarg.0
IL_0001: ldtoken [mscorlib]System.String
IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000b: callvirt instance string [mscorlib]System.Object::ToString()
IL_0010: call bool [mscorlib]System.String::op_Equality(string,
string)
IL_0015: stloc.0
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: ret
} // end of method Program::'<Main>b__0'
Лямбда-выражение в MSIL, Конфигурация выпуска:
.method private hidebysig static bool '<Main>b__0'(string a) cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldtoken [mscorlib]System.String
IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000b: callvirt instance string [mscorlib]System.Object::ToString()
IL_0010: call bool [mscorlib]System.String::op_Equality(string,
string)
IL_0015: ret
} // end of method Program::'<Main>b__0'
Обе версии называют typeof(String).ToString())
, эта лямбда вызывается на каждой итерации. Никакой оптимизации на уровне IL, компиляция JIT ничего не добавит. Причина в том, что функция может иметь побочные эффекты.