Are typed ArrayLists a good idea?

I love ArrayLists. I find them to be among the most useful collections in the .NET Framework. I remember seeing a discussion somewhere a few months ago about making ArrayLists into strongly-typed collections. This was achieved by simply inheriting ArrayList and overriding the Add/Insert methods to make sure the objects being added were a particular type.

I don't know enough about what's going on under the hood to know if there's a performance penalty involved with this. Is checking the type of an object an expensive process?

7 Comments

  • Heh, they're one of the *only* collections in the .NET framework :).



    Typed collections are usually a pretty good idea. They make it so that the compiler can tell you when you accidentally put something in the list that you didn't mean to.



    In the next version of the framework, there will be Templates, and you won't need to inherit array list to create strongly typed collections at all. You will wonder how you ever did without.

  • Frans,



    Are you sure about that? From looking at Reflector, I don't see any evidence that ArrayList.Add() checks for a duplicate value. Nor does it appear to derive from CollectionBase.

  • Zknet: Check the members of CollectionBase. It has a protected 'List' property of the type ArrayList.

  • I see now. List is IList, but InnerList & list are ArrayLists. Missed those before. Thanks.

  • ArrayList in C# is designed with reference types in mind.Using ArrayList with value types leads to unnecessary boxing and unboxing, which degrades performance.

  • I am coming to this discussion late but wanted to chime in. I recently rolled off a project where I spent six months in the role of performance engineer on an enterprise .net project. This very argument raged on for weeks before I created a test application which created several different collection implementations, including typed collections, and cycled through them several million times. It's been a while so some of the details are lost, but the most startling thing was that the ArrayList, in any capacity, was in that small group that had great performance. In reference to the boxing, this brings the performance of any collection to its knees. This is an incredibly easy test to put together, and I would welcome any feedback from the readers of this blog as I still consult on performance. I agree that when you know the type, typed collections are the way to go, but overall, the ArrayList is one that i too have come to love in the .net framework.

  • to pottman:

    Did you have Templates i your performance test? I would be curious to compare Typed ArrayList and Templated collection performace. Did anyone hear about such tests?

Comments have been disabled for this content.