move length compuatation to outside a loop