for循环与foreach的性能 [英] Performance of for loop vs foreach

查看:124
本文介绍了for循环与foreach的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



for或foreach哪个性能更好?

在此先谢谢您.

Hi,

Which has better performance for or foreach ?

Thanks in Advance.

推荐答案

foreach将要创建一个新对象,并且与此相关的费用.
一些枚举程序将检查解决方案是否已更改,并且还会产生成本.
这就是说,不要落入这个陷阱.我曾经有一个学生决定将所有foreach(更改为for(int x=1;....
它使代码更难阅读,并且带来的好处并不明显.

性能调整的秘诀是首先确定哪些位较慢.
然后,只有到那时,您才可以对这些位进行操作,并使其余部分不受干扰.
foreach wil be creating a new object and there is a cost associated with this.
Some enumerators will check if the solution is changed and there are also a cost for it.
This said, don''t fall to quick into this trap. I had a student once who decided to change all the foreach( into a for(int x=1;....
It made the code harder to read and the benefit was not noticeable.

The secret of performance tweaking is to first identify which bits are slow.
Then and only then you can act on these bits and leave the rest undisturbed.


FOREACHVS. FOR(C#) [^ ]

For-vs-ForEach-performance/ [
FOREACH Vs. FOR (C#)[^]

For-vs-ForEach-performance/[^]


您是程序员.编写一个使用每种有问题的方法的应用程序,然后自己看看.另外,您也可以在Google上搜索它.
You''re a programmer. Write an app that uses each of the methods in question and see for yourself. Alternatively, you can just google it.


这篇关于for循环与foreach的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆