Friday, January 21, 2005

.NET 2.0 Generics samples & Performance Comparison

One of the most awaited features of Microsoft .NET 2.0 is generics. Starting with VS 2005, C#, Managed C++, and VB will have CLR support for generics.

Generics promise to increase type safety, improve performance, reduce code duplication(code reuse) and eliminate unnessecary casts(boxing). The most obvious application of generics in the framework class library are the generic collections in the new System.Collections.Generic namespace.

While Generic types do have a similar syntax to C++ templates, they are instantiated at runtime as opposed to compile time (by Microsoft's C++ compiler), and they can be reflected on via meta-data. Also, in Generics, member access on the type paramater is verified based on the constraints placed on the type parameter; whereas, in templates, member access is verified on the type argument after instantiation. When the MS C++ compiler creates a separate type for every template specialization, that does not necessarily mean every type emits separate code. In fact, you'll find that through a feature called COMDAT folding, most templates share quite a bit of code. (Basically, the myth of code bloat for templates isn't true these days.) By having separate specializations of code at compile-time, the compiler has the ability to optimize each type individually, which includes inlining. If every instance of a function is inlined, the template code is thrown away by the linker resulting in less code. For these reasons, template code is generally much faster and leaner than an equivalent generic alternative.

C++ templates are a compile-time feature much like a macro preprocessor and are thus not a good solution for a highly dynamic language such as C#.

In .NET, for value types, generics is considerably faster, and for reference types, generics is typically comparable in performance—or faster.

Good Links:

Introducing Generics in the CLR

Generics Performance Results and a sample to test other collections

Generics Performance (CSharp)

The problem with .NET generics

A generic Set type for .NET

6 questions about generics.

Performance: Interfaces Vs. Inheritance (Abstract Base Classes) Vs. Generics

Thanks to the authors for the above links.

No comments: