.NET Inside Out Part 10 — Using type markers for low level optimizations

This is the tenth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

If you are interested in the topic see the talk page

Today we are going to see a concept of type markers which we can use for low level optimizations. They are somewhat similar to templates in C++ and allow some very basic meta programming in C#. Let’s see the following code:

We have a simple method which chooses one of two integers based on the generic type. When we decompile this we can see the following:

We can see that we call ChooseClass method using the same address. No surprise here — generic method doesn’t care about parameters and JIT compiler emits just one code for all types. If we decompile it we get:

So we can see that we get runtime type and compare it with LeftClass.

However, things are different with structs. JIT cannot emit the same code for two different struct types because they differ in memory storage under the hood (they are values). So let’s try this:

And now we get:

Notice that now addresses are different! If we decompile ChooseStruct for LeftStruct we get this:

and for RightStruct we get:

Notice that parameters are different: we return ecx or edx, first and second parameter respectively.

JIT is able to optimize the method significantly because it knows what type it is dealing with. Next time we will see how we can use this thing to optimize code.