i was making some optimizations to an algorithm that finds the smallest number that is bigger than X, in a given array, but then a i stumbled on a strange difference. On the
The reason for this difference is that your for
loop will execute bigList.Count()
at every iteration. This is really costly in your case, because it will execute the Select
and iterate the complete result set.
Furthermore, you are using ElementAt
which again executes the select and iterates it up to the index you provided.
IEnumerable<T>
is not indexable.
The Count()
and ElementAt()
extension methods that you call in every iteration of your for
loop are O(n); they need to loop through the collection to find the count or the nth element.
Moral: Know thy collection types.