C# - For vs Foreach - Huge performance difference

前端 未结 2 1492
心在旅途
心在旅途 2020-12-10 03:16

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

相关标签:
2条回答
  • 2020-12-10 03:42

    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.

    0 讨论(0)
  • 2020-12-10 03:44

    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.

    0 讨论(0)
提交回复
热议问题