bug 59773: move loop invariants out of for-loop for performance, use for-each instead of for loop when possible