Tuesday, July 15, 2008

Comparing the ArrayList and List (generic) collections in .NET

If you've started developing on .NET since version 1.0 or 1.1 of the framework, the ArrayList has probably been a favorite for you till .NET 2.0 when the fans switched flags to join the generic camp with the List class.

Looking at the implementation of the two classes, both internally use arrays. While the ArrayList uses an object array, the List uses a generic-typed array. The List therefore, supposedly (in theory... but probably due to issues in implementation of the compiler or framework, does not), gives you better performance as you get back the objects in the type that you inserted them thus saving you a type-cast operation. The performance benefits of generics over objects is a little disputed topic in the .NET framework - several others have demonstrated almost no performance benefit in the use of generics, but the key advantage we see here is compile-time validation of assignments based on data type as opposed to run-time validation of the variable assignments.

I still remember the software engineering course that I took up when I first used generics on an assignment. The instructor was visibly upset - they were using an old compiler for evaluation and when I asked them to get a brand new shiny compiler to support new language features, the argument from them is "That is such an archaic concept from the world of C++... Are you insane? We're teaching software engineering here, not computer programming 101". Sure, generics are opposed by some group of people but if they've got a better solution, they have yet to present it.

No comments: