简体   繁体   English

在使用foreach之前,我应该检查集合计数吗?

[英]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.

相关问题 我是否需要在foreach之前检查Enumerable的Count() - Do I need to check the Count() of an Enumerable before foreach NUnit:在断言中使用对象之前,我是否应该检查对象是否不是 null? - NUnit: Should I check that objects are not null before using them in asserts? 我应该在Invoke()之前检查InvokeRequired吗? - Should I check InvokeRequired before Invoke()? 我应该在删除之前检查用户是否存在吗? - Should I check if a user exists before deleting it? 性能 - 在使用 foreach 循环之前检查列表是否为空 - Performance - before using a foreach loop check if the list is empty 在使用ForEach Lambda表达式之前如何检查列表对象不为null - How to check list object is not null before using ForEach lambda expression 在调用自定义事件之前,为什么要检查null? - Why should I check for null before I invoke the custom event? 在访问之前,我应该检查Dictionary中是否存在特定键吗? - Should I check whether particular key is present in Dictionary before accessing it? 为什么要在调用 ThrowIfCancellationRequested() 之前检查 IsCancellationRequested - Why should I check IsCancellationRequested before calling ThrowIfCancellationRequested() 我应该在设置之前检查 VisualElement.IsVisible 吗? - Should I check VisualElement.IsVisible before setting it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM