I wonder if there would be much performance benefit from moving this check outside of the loop. We could either have two loops or factor out the common parts into a helper.