11.9. Performance

Although there are a number of advantages to using generics, their performance benefits may represent their most compelling characteristic. In environments where you're trying to eke every last millisecond out of your algorithms, you'll find generics can actually provide significant performance gains—especially when it comes to populating and accessing large data containers.

The primary factor that impacts the performance of existing structures is their dependency on representing all contained types as objects. If, for example, you've got some structure you're using to represent the points on a chart and you're holding a collection of 300,000 of these items in an ArrayList, you're paying a stiff penalty as you move data into this list and as you access data in that structure.

Each time a value type is placed into an ArrayList, that list must box each value type. Then, as you access the data for that type, you're going to take on the overhead of unboxing it as it morphs from an object back into its original value representation. You might think the performance hit associated with this boxing and unboxing is nominal—it's not.

As a point of comparison, consider how these same 300,000 value types would be managed by a generic List<T> collection. With a generic collection, there's no need for any boxing. Instead, the value types are represented in IL in the native form for their entire life cycle. The chart in Figure 11-3 attempts to provide some more concrete assessment ...

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.