Removing var assingment from loop and calculating buffer length outside the loop