Thursday, December 14, 2017

typeof vs nameof


Skip to end of metadata

Go to start of metadata
Recently had a discussion with a fellow dev regarding the difference between typeof(T).Name and nameof(T).
It is a lot more performant to use nameof keyword if you are just trying to get the string name of type as opposed to typeof(T).Name.

Let's look at an following example.

Given a simple C# console app as follows:
a console app
1
2
3
4
5
6
7
8
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(typeof(Program).Name);
        Console.WriteLine(nameof(Program));
    }
}

The compiler generates the following IL:
generated IL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       34 (0x22)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldtoken    typeof_nameof.Program
  IL_0006:  call       class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
  IL_000b:  callvirt   instance string [mscorlib]System.Reflection.MemberInfo::get_Name()
  IL_0010:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0015:  nop
  IL_0016:  ldstr      "Program"
  IL_001b:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0020:  nop
  IL_0021:  ret
// end of method Program::Main

Notice nameof is turned into a string "Program"? while typeof(Program).Name generated code to execute get_Name(). typeof is definitely a runtime evaluation.
Naturally string literal requires almost zero calculation at runtime therefore it is a more performant one.  In conclusion, we should favor it over typeof(T).Name

No comments:

Post a Comment

About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers