简体   繁体   中英

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?

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.

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. 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM