MSIL String comparison question
-
Hey geniuses, it's me again. Google has failed me so I humbly come to you with a question about how .NET performs string comparisions. A tiny bit of background, I'm reseaching how the use of string constants is better than hardcoding string literals (beyond good coding practice). I wrote this code to check the various ways .NET handles strings.
string s = "howdy";
if (HELLO_W == "hello")
{
Console.WriteLine("condition 3");
}And then checked the IDL with ildasm.exe
IL_0033: ldstr "howdy"
IL_0038: stloc.1
IL_0039: ldc.i4.0
IL_003a: stloc.2
IL_003b: nop
IL_003c: ldstr "condition 3"
IL_0041: call void [mscorlib]System.Console::WriteLine(string)
IL_0046: nopSo where is the string comparision? When I compare two ints, I see the comparision command "ceq". As always, I appreciate your insights and am not afraid to kiss a little butt to get it. ;P
-
Hey geniuses, it's me again. Google has failed me so I humbly come to you with a question about how .NET performs string comparisions. A tiny bit of background, I'm reseaching how the use of string constants is better than hardcoding string literals (beyond good coding practice). I wrote this code to check the various ways .NET handles strings.
string s = "howdy";
if (HELLO_W == "hello")
{
Console.WriteLine("condition 3");
}And then checked the IDL with ildasm.exe
IL_0033: ldstr "howdy"
IL_0038: stloc.1
IL_0039: ldc.i4.0
IL_003a: stloc.2
IL_003b: nop
IL_003c: ldstr "condition 3"
IL_0041: call void [mscorlib]System.Console::WriteLine(string)
IL_0046: nopSo where is the string comparision? When I compare two ints, I see the comparision command "ceq". As always, I appreciate your insights and am not afraid to kiss a little butt to get it. ;P
If
HELLO_W
is a constant, then the result of the comparison is known at compile time and it will always be the same. I believe the compiler is smart enough to remove such unnecessary conditions... You might get different IL code depending on the compiler settings (Release/Debug). -
If
HELLO_W
is a constant, then the result of the comparison is known at compile time and it will always be the same. I believe the compiler is smart enough to remove such unnecessary conditions... You might get different IL code depending on the compiler settings (Release/Debug).Yep, that was it. Thank you. Now I'm getting this.
IL_004a: call bool [mscorlib]System.String::op_Equality(string,string)
Rookie mistake.
-
Yep, that was it. Thank you. Now I'm getting this.
IL_004a: call bool [mscorlib]System.String::op_Equality(string,string)
Rookie mistake.