From what I can read the compiler just emits a string and nothing else really happens?
Is there any reason that the results of this call couldn't be interned? For a nameof(MyClass)
, if it happens a lot, it could, theoretically be worth it?
Yes, it will be interned just as any other string literal.
This can be demonstrated with this TryRoslyn example where this:
public void M()
{
Console.WriteLine(nameof(M));
}
Is complied into this IL:
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x2050
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldstr "M"
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
} // end of method C::M
You can see that "M"
is being loaded using ldstr
which means it is interned:
"The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning")."
From OpCodes.Ldstr Field
This can also be verified by running this example, which prints true
:
Console.WriteLine(ReferenceEquals(nameof(Main), nameof(Main)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With