Arrays Vs Lists – Which one to use?

Both Arrays and Lists helps us to store list of elements. But which one to choose is an important design decision that is directly related to application performance.

Arrays are strongly typed – meaning they can only store data of one type. Use Arrays where the size and type of elements is fixed and we need to search through the elements based on the index and there is little need to insert/delete elements into the array.

eg: var numbers = new[4] {2,3,4,5};

Lists are generic type and store a particular type of data also. Use Lists if the size of the array is dynamic and we need to insert/delete elements into the list very often. Array assigns contiguous memory locations and is faster as its obvious when we use for indexed search. Whereas List is not as fast as Array, but has it own performance advantage as noted above.

ArrayLists (storing any type of data) are deprecated >= .NET 2.0 and generic List<> types are encouraged due to performance overhead in boxing/unboxing of object type and List types’ easy usage with LINQ.

eg: var blocks = new List() {2,3,4,5}

blocks.AddRange(new[4] {6,7,8,9});

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *