[英]Should I check the Count of the collection before using foreach?
Would there be any performance improvement to add a check of the count of a collection before enumerating the contents with foreach? 在使用foreach枚举内容之前,添加集合计数检查是否会有任何性能改进?
if (users.Count != 0) {
foreach (var user in users) {
// do what snowmen do in summer
}
}
vs. 与
foreach (var user in users) {
// do what snowmen do in summer
}
My function is taking a little too long, so I'd like to know if this will improve performance even a little to get my function execution time down to where I need it. 我的函数花费的时间太长,所以我想知道这是否会提高性能甚至使我的函数执行时间减少到我需要的时间。
Edit (context in which this loop executes): 编辑(执行此循环的上下文):
for (DateTime day = dayStart; day < dayEnd; day = day.addMinutes(30)) {
// Other actions
if (users.Count != 0) {
foreach (var user in users) {
// do what snowmen do in summer
}
}
}
The two scripts have the same results. 这两个脚本具有相同的结果。
Foreach will not do anything if the count is zero, so no need for if statement. 如果计数为零,则Foreach将不执行任何操作,因此不需要if语句。
It is not faster the difference of execution in nano seconds and bigger, it will be slower in case the list have items but you will not notice anything in the two cases. 执行差异(以纳秒为单位)和更大之间的差异并不快,如果列表中有项目,则差异会变慢,但是在两种情况下您都不会注意到任何事情。
The first version is probably a degradation. 第一个版本可能是降级版本。
Chances are great that the first instruction in the foreach is a quick test for emptiness. 很有可能foreach中的第一条指令是对空虚的快速测试。 So you are essentially repeating twice the same. 因此,您实质上是在重复两次相同的操作。
In any case, such an "nano-optimization" has no visible effect in practice. 在任何情况下,这种“纳米优化”在实践中都没有可见的效果。
(Unless in a large majority of the cases, Count is zero.) (除非在大多数情况下,Count为零。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.