tags:

views:

453

answers:

2

Why is the generic.list slower than array?

+4  A: 

A generic list is slightly slower than an array, but not so you'd notice in most cases. Mostly it has to do with the lookup being slightly more complex: List is said to use an array "under the hood", but it's not not guaranteed to keep nodes in adjacent memory in the same way in array is.

However, I saw some benchmarks way back in 2005 (can't find the link now) and difference is very small.

Also, the list has a number of important advantages over an array: mainly that it's trivial to add or remove items. It's much easier to use a list when you don't know how many items you will need, or when that number will vary. In those cases (and honestly, that's most of the time), you probably should not use an array.

Joel Coehoorn
good answer, since you have enough points, maybe you could edit the question.
Lance Roberts
I wasn't sure enough what the original meaning was. Yes, I know that seems odd as I've provided an answer, but providing an potentially incorrect answer wouldn't destroy the question like an edit would.
Joel Coehoorn
Well, the main data block (the array) will be jut a s contiguous - but agreed: it probably isn't adjacent to the List<T> instance.
Marc Gravell
+2  A: 

In terms of read performance, there are two factors:

  • an extra dereference (i.e. the List<T> will contain a T[] field, and has to de-reference it)
  • it can't use some compiler optimisations that that exist for T[] - such as eliminating bounds checking during loops

However, it is much easier to add to a List<T>, in particular because it retains spare space - i.e. it doesn't have to resize/blit the entire array just to add a single element.

Marc Gravell