Why is the generic.list slower than array?
-
grammar? you question is barely comprehensible as is.Joel Coehoorn– Joel Coehoorn2008-11-06 17:24:56 +00:00Commented Nov 6, 2008 at 17:24
-
Probably need to give slack to non-english speaker.Lance Roberts– Lance Roberts2008-11-06 17:26:49 +00:00Commented Nov 6, 2008 at 17:26
-
1How else will one's english get better, if no one tells them when it's especially bad?Joel Coehoorn– Joel Coehoorn2008-11-06 17:28:03 +00:00Commented Nov 6, 2008 at 17:28
-
Good point, I think editing the question to be readable would probably help the most.Lance Roberts– Lance Roberts2008-11-06 17:28:55 +00:00Commented Nov 6, 2008 at 17:28
-
Give slack? For using Y? Come on.Alan– Alan2008-11-06 17:29:28 +00:00Commented Nov 6, 2008 at 17:29
2 Answers
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.
3 Comments
In terms of read performance, there are two factors:
- an extra dereference (i.e. the
List<T>will contain aT[]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.