According to the answers in this post, List<T>
is backed by an Array. According to this article, list iteration is considerably slower than array iteration.
If Lists are arrays 'under the hood', why do they take longer to iterate over, especially with foreach?
Note: This is assuming Lists are implemented with Arrays. I might have just interpreted the information wrong.
1 Answer 1
Iterating through a List is (slightly) slower than a plain array due to a few factors:
Bounds checks: This is likely to be the biggest factor; every single indexer access to the List is going to do a bounds check. Bounds checking on a raw array can often be trivially optimized out of a loop by the JIT.
Method call costs: The indexer on a List is a method call. This might get inlined, but it also might not.
An extra indirection: In order to get to the array inside the List, you need to dereference the List reference. With an array, you have a reference directly to the necessary data.
Potentially an extra copy of the element: When you use the List indexer, you get a copy of the element back. With an array, you can access the element directly in memory. Depending on what the rest of your code looks like, you can avoid making a copy of that data.
When using the Enumerator to iterate, your costs are mostly dominated by the aforementioned bounds check as well as the "version" check to make sure you haven't modified the list while iterating over it.
-
Thanks for the thorough answer. I guess the articles I read are a bit outdated but it's interesting that just going through the 'hood' requires this much to be done and creates that much overhead.JPtheK9– JPtheK92015年05月11日 22:38:51 +00:00Commented May 11, 2015 at 22:38
Explore related questions
See similar questions with these tags.
for
loop is still faster than reading lists (~4 to 5 times on my machine for an int array). However, in most real world situations, the difference is irrelevant.