Magic-Mouse
Magic-Mouse

Reputation: 613

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
    }
  }
}

Upvotes: 1

Views: 862

Answers (2)

user1196549
user1196549

Reputation:

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

Upvotes: 0

oussama abdou
oussama abdou

Reputation: 327

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.

Upvotes: 10

Related Questions