Don't check emptyness before loops

An opinion piece on code style matters.

If your plan is to loop over a collection: You shouldn’t check for it being non-empty first.

Don’t do this:

if (!stuff.empty()) {
  for (Item item : stuff) {
    // ...
  }
}

Do this instead:

for (Item item : stuff) {
  // ...
}

Benefits:

I used to do this too at some point in the past, because I thought this would have performance benefits, but in reality, the performance benefit is hardly measurable and generally falls into the category “premature optimization”.

Even if there is a little extra code happening between the if and the for, the performance impact needs to be significant for this to make a difference in most cases, and it’s probably not worth the additional code convolution.

Comments