optimize code by reduce re-computation of length