当前位置: 首页 > 编程语言 > C#

For vs Foreach – 巨大的性能差异分享

时间:2023-04-10 19:41:32 C#

C#学习教程:C#-ForvsForeach-巨大的性能差异在下面的代码中,“ForeachUpper”以625毫秒结束,而“ForUpper”结束,我相信,以小时为单位(非常慢)。为什么这样?classTeste{publicdoubleValor{get;放;}publicTeste(doubled){Valor=d;}publicoverridestringToString(){return"Teste:"+Valor;}}privatestaticIEnumerableGetTeste(doubletotal){for(inti=1;id.Valor),test);Console.WriteLine("------------");ForUpper(ieTeste.Select(d=>d.Valor),测试);控制台.Read();}privatestaticvoidForUpper(IEnumerablebigList,doublefind){varstart1=DateTime.Now;双上层=0;for(inti=0;i=find){uppper=toMatch;休息;}}varend1=(DateTime.Now-start1).TotalMilliseconds;Console.WriteLine(end1+"="+uppper);}privatestaticvoidForeachUpper(IEnumerablebigList,doublefind){varstart1=DateTime.Now;双上=0;foreach(vartoMatchinbigList){if(toMatch>=find){upper=toMatch;休息;}}varend1=(DateTime.Now-start1).TotalMilliseconds;Console.WriteLine(end1+"="+upper);}谢谢IEnumerable不可索引。在for循环的每次迭代中调用的Count()和ElementAt()扩展方法是O(n);他们需要遍历集合来找到第count个或第n个元素。道德:了解您的收藏类型。造成这种差异的原因是您的for循环将在每次迭代时执行bigList.Count()。在您的情况下,这是非常昂贵的,因为它将执行Select并遍历整个结果集。此外,您正在使用ElementAt,它再次执行选择并将其迭代到您提供的索引。以上就是C#学习教程的全部内容:C#–ForvsForeach–巨大的性能差异。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: