O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required