0

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?

Stephn
  • 3
  • 1
  • 1
    There's a built-in `reverse()` method. – Barmar Jan 11 '21 at 22:45
  • The best way is to test yourself! I'm guessing that `Array.prototype.reverse()` is the fastest, otherwise it would not need to exist. – Guerric P Jan 11 '21 at 22:45
  • That strongly depends on how you do it. A clever implementation of in place reverse will probably faster than a badly implemented usage of a new array and vice versa – derpirscher Jan 11 '21 at 22:46
  • Creating a new array has to allocate additional memory, possibly multiple times as the array grows, updating in place doesn't. So it's hard to imagine how a new array could be more efficient than in-place. – Barmar Jan 11 '21 at 22:48
  • Can you provide the source code please? – vbuzze Jan 11 '21 at 23:15

2 Answers2

0

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.

ultra_rn
  • 322
  • 1
  • 7
0

Assuming your code is optimized:

  • The second option has a better space complexity (1: O(n^2), 2: O(n+1)).
  • The second option has a better time complexity (1: O(n), 2: O(n/2)).

Also note that may use the built-in Array.prototype.reverse() method as well.

vbuzze
  • 930
  • 1
  • 11
  • 25