Optimization by using in-place operations instead of allocating new arrays