I have been trying to reverse an array, first by using push and creating a new array, and then second by using destructuring and mutating the original array.
I'm wondering which of the two runs faster, and why?
I have been trying to reverse an array, first by using push and creating a new array, and then second by using destructuring and mutating the original array.
I'm wondering which of the two runs faster, and why?
Assuming that you mean the push helper method to create a new array by iterating through the given array. Using this method you have to traverse the entire array in order to reverse it. The time complexity is O(n). Reversing an array in place also takes O(n) time as well even though it only requires half of the array to be traversed. This is because O(n/2) can be simplified to O(n). Therefore the time complexity is the same although strictly speaking reversing in place takes less time.
Assuming your code is optimized:
O(n^2)
, 2: O(n+1)
).O(n)
, 2: O(n/2)
).Also note that may use the built-in
Array.prototype.reverse()
method as well.