Monday, October 16, 2006
Array vs. ArrayList
We use .NET Array and ArrayList objects quite often, but sometimes do not realize the benefits versus consequences of using one or the other. This article explains the differences between these two data structures enabling us to make an informed decision the next time we are required to choose between the two. An Array is generally a light-weight (as compared to ArrayList), strongly-typed data structure that can hold a pre-defined number of pre-determined element types. Arrays generally perform faster at run-time and consume lesser memory as compared to ArrayLists. Also since arrays can be strongly typed, they can take advantage of compile time validation. An ArrayList is a class that implements a dynamic collection of objects, that can expand or contract on demand. The type of elements that can be stored in an ArrayList is always System.Object, hence elements retrieved must usually be casted to their original types. ArrayList implements the IList interface (which is a descendant of the ICollection and IEnumerable interfaces), hence the number of elements that can be stored in an ArrayList can be altered (and enumerated) on demand. This flexibility, however, comes at the price of some run-time performance. Internally, ArrayList objects use arrays to store data. By default, an ArrayList initially creates an array of 16 elements (.NET 1.x and perhaps 2.0) and then modifies it directly as needed. Once the internal array gets filled, the ArrayList automatically creates an internal array of double the previous size and copies elements from the old array to the new one. This operation obviously is a slight hit on performance as well as memory. .NET 2.0 introduced Generic Lists, which make it possible to store and retrieve typed objects, hence allowing compile time validation and eliminating the need to cast objects back to their original types. There are various generic lists available in the System.Collections.Generic and System.Collections.ObjectModel namespaces which are suitable for various scenarios. Generally when programming in .NET 2.0, these generic collections are preferred over ArrayList objects.