.NET Performance – Why Iterating Through List is More Expensive Than Array

arrayiteratorlistnetperformance

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.

Best Answer

Iterating through a List is (slightly) slower than a plain array due to a few factors:

  1. 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.

  2. Method call costs: The indexer on a List is a method call. This might get inlined, but it also might not.

  3. 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.

  4. 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.

  5. 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.

Related Topic