11.8. NGen and Generic Types

The .NET SDK includes the NGen tool that allows developers to generate native x86 versions of their code. Developers might choose to use this tool for a variety of reasons. And, of course, there's also a great deal of debate that surrounds how and when—or even if—NGen should be applied. Regardless of what's motivating your desire to use NGen, you're likely to want to understand how the tool will process the generic code that's part of your solutions.

With NGen, there can't be anything "lazy" about how generics are instantiated. Instead, NGen must create representations of every generics instance it could encounter. The CLR won't be around to JIT anything. So, after all the discussion of avoiding code bloat and taking advantage of CLR's run-time optimizations, NGen takes all those values and turns them on their collective heads.

Even with NGen, though, there can be some degree of code sharing. Reference types, for example, can still share code. So, while you still get the code bloat associated with precompiling every instance, you get some efficiency out of the fact that these reference types will still be using shared code.

For value types, where you can't share code, there's more motivation to avoid precompiling those types that are not needed. To achieve this, NGen will compute the set types that are required for a given assembly (using transitive closure) and precompile just those instances. This will minimize the amount of bloat you'll take on ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.