I copied the exact code, ran its Release without a debugger (both important!) And on x64. Results:
Without box: 00:00:07.9650541 With box: 00:00:16.0958162
Test change to:
[MethodImpl(MethodImplOptions.NoInlining)] private static void TestBox(MyBox box) { if (box.Value.GetType() == typeof(double)) TakeDouble((double)box.Value); else if (box.Value.GetType() == typeof(MyObject)) TakeObject((MyObject)box.Value); }
Reduces lead time:
Without box: 00:00:07.9488281 With box: 00:00:08.6084029
Why? Because JIT decides not to embed IsDouble , but manual embedding helps. This is strange because it is such a small function. call on line 13 is the call.

Now why is there still a difference in performance? .NET JIT is not the best compiler out there ... maybe some instructions are a little different. You can find out by comparing the disassembly of the two versions. I will not have time for this, because I expect that the difference will be completely uninteresting.
I would expect the C compiler to get this right. The structure should behave as a separate element of the object that it contains. Small methods should be built in. This is definitely doable with today's compiler technology. Let's hope that the next generation of JIT and NGEN can do this. A new JIT (RyuJIT) is being developed and they are promoting optimization from the VC backend to NGEN (recently announced).
usr
source share