C# - For vs Foreach - Huge performance difference

前端 未结 2 1495
心在旅途
心在旅途 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.

提交回复
热议问题