哪个循环需要更多时间? [英] Which loop take more time?

查看:90
本文介绍了哪个循环需要更多时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个循环花费更多的时间用于foreach?

Which loop take more time for of foreach?

推荐答案

我假设你的问题中有一个拼写错误并且想要问哪个循环花费更多时间< b>或 foreach?



显然,for循环与foreach循环不同,它并不总是(很容易)交换一个为另一个。在 容易实现的情况下,for循环(通常)比foreach循环略快,因为它(通常)只增加或减少整数变量,但foreach循环需要一个枚举器。根据你在循环中的操作,for循环可以有额外的性能优势。



我建议:如果循环中的代码不是性能 - 尽可能使用foreach-loop,因为它(IMO)更直观易读。否则,如果可能,请使用for循环。并且:在认识到性能确实是一个问题之前,不要费心去优化。
I assume you have a typo in your question and meant to ask "Which loop take more time for or foreach?"

Obviously, a for loop is a different thing than a foreach-loop and it's not always (easily) possible to exchange one for the other. In cases where it is easily possible, a for-loop is (usually) slightly faster than a foreach-loop because it (usually) just increments or decrements an integer variable but a foreach-loop requires an enumerator. Depending on what you do inside the loop, the for-loop can have additional performance-benefits.

I would suggest: If your code inside the loop isn't performance-critical use a foreach-loop if possible because it is (IMO) more intuitive to read. Otherwise use a for-loop if possible. And: Don't bother with optimization before you recognize that performance really is an issue.



递减速度比递增速度快,这比foreach更快无论迭代是什么,这都是正确的。



...



最重要的是永远记住并且永远不要忘记foreach的可读性是以比慢速为代价的 - 两个(黄色和绿色)技术之间的差异是20倍。

- < a href =http://www.codeproject.com/Tips/850878/On-Why-to-Use-DataViews>关于使用DataViews的原因 [ ^ ]


你可以看到下一篇文章中的基准测试结果:

For Vs Foreach - 基准2013 [ ^ ]
You can see the benchmark results about this in the next article:
For Vs Foreach - Benchmark 2013[^]


这篇关于哪个循环需要更多时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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