Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article describes performance insights for Enumerable.ElementAt.
Cause
When using the Enumerable.ElementAt extension method, the method attempts to leverage the underlying container's fast lookup mechanism if available, such as List<T>.Item[], which has O(1) access. If unavailable, the method evaluates the enumerable starting at the beginning of the collection and enumerates to the desired element resulting in O(n) access.
Performance insight description
The Enumerable.ElementAt extension method is designed to try and use the fastest access available to access the specified element. For underlying collections such as List<T>, it can use List.Item[] direct access, which has O(1) access time. If the underlying collection doesn't support direct access such as LinkedList<T> or IEnumerable<T> from a yield statement, it must start at the beginning of the collection and iterate through to the desired index, resulting in O(n) lookup time. If this warning fires, utilizing a better collection can result in better performance.
How to investigate a warning
In the CPU Usage tool, click View source code to go to the call tree and source line highlighting view that shows where the most amount of time is being spent in Enumerable.ElementAt. From this point, trace back to where the underlying enumerable collection is created and investigate whether a more appropriate data structure such as List can be used instead.