5

I just asked C# - How do generics with the new() constraint get machine code generated?

After thinking about this for a while, I'm wondering why the C# Compiler emitted IL like that.

Why couldn't it say some IL like: "Call T's default constructor"?

Community
  • 1
  • 1
halivingston
  • 3,727
  • 4
  • 29
  • 42

1 Answers1

2

There is no such instruction in CIL (http://www.ecma-international.org/publications/standards/Ecma-335.htm).

Assuming we can add one, an another implementation of this could be that in the Type's VTable we make the default constructor be indexed at index 0, and then the JIT can assume this information and emit code that does a VTable lookup, pick index 0 and call the function located at address pointed by this entry 0 in the VTable.

As you can see this requires a change in CLR data structures, possibly each object's layout, and likely a different solution for value types (I'm ignoring that case, because you specifically say class and new().

mjsabby
  • 1,139
  • 7
  • 14
  • 1
    And the JIT could optimize the CreateInstance call away which would result in optimal performance. No idea if this is being done. Probably not since we are talking about the .NET JIT. If in doubt, it's a safe bet that it will not optimize. Update: Turns out that the C# compiler does a part of this optimization because the JIT fails to: https://www.simple-talk.com/blogs/2010/11/17/subterranean-il-constructor-constraints/ – usr Sep 13 '15 at 22:09