hoist boundary check code to the out of loop