for loop optimizations

Moved var declarations out of loops. Saved all .lengths clauses as a
var.