C# - For vs Foreach - Huge performance difference

前端 未结 2 1501
心在旅途
心在旅途 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:44

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

提交回复
热议问题