rewrite loop to go through only once

This is a performance improvement, apparently significant if the form has many nodes (1000s)