C# performance: comparing string.Empty with double quote (empty string)
In the spirit of performance, there is a funny point about string comparaison.
In the left corner, string.empty comparison.
- string myValue = "I love C#";
- if (myValue != String.Empty)
- Console.Out.WriteLine("I'm loving it!");
and in the right corner double quote comparison:
- string myValue = "I love C#";
- if (myValue != "")
- Console.Out.WriteLine("I'm loving it!");
With a loop with 500000 iterations, execution time for string.empty comparaison is more than 5% than double quote comparaison.
Why ?
Have a look in the IL Code:
string.empty comparison:
- .method private hidebysig static void Main() cil managed
- {
- .entrypoint
- // Code size 42 (0x2a)
- .maxstack 2
- .locals init ([0] string myValue,
- [1] bool CS$4$0000)
- IL_0000: nop
- IL_0001: ldstr "I love C#"
- IL_0006: stloc.0
- IL_0007: ldloc.0
- IL_0008: ldsfld string [mscorlib]System.String::Empty
- IL_000d: call bool [mscorlib]System.String::op_Inequality(string,
- string)
- IL_0012: ldc.i4.0
- IL_0013: ceq
- IL_0015: stloc.1
- IL_0016: ldloc.1
- IL_0017: brtrue.s IL_0029
- IL_0019: call class [mscorlib]System.IO.TextWriter [mscorlib]System.Console::get_Out()
- IL_001e: ldstr "I'm loving it!"
- IL_0023: callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string)
- IL_0028: nop
- IL_0029: ret
- } // end of method Pro
- gram::Main
double quote comparison:
- .method private hidebysig static void Main() cil managed
- {
- .entrypoint
- // Code size 42 (0x2a)
- .maxstack 2
- .locals init ([0] string myValue,
- [1] bool CS$4$0000)
- IL_0000: nop
- IL_0001: ldstr "I love C#"
- IL_0006: stloc.0
- IL_0007: ldloc.0
- IL_0008: ldstr ""
- IL_000d: call bool [mscorlib]System.String::op_Inequality(string,
- string)
- IL_0012: ldc.i4.0
- IL_0013: ceq
- IL_0015: stloc.1
- IL_0016: ldloc.1
- IL_0017: brtrue.s IL_0029
- IL_0019: call class [mscorlib]System.IO.TextWriter [mscorlib]System.Console::get_Out()
- IL_001e: ldstr "I'm loving it!"
- IL_0023: callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string)
- IL_0028: nop
- IL_0029: ret
- } // end of method Progra
- m::Main
Only one line difference.
In double quote comparaison, the "" value is loaded from the stack.
In string.empty comparaison, the string.Empty object reference is loaded from metadata.
Loading from metadata is longer than loading from the stack.
If you are on a real time server and you want absolute performance, 5% is important. In another cases, string.empty comparaison is safe and your code will be more readable.