Skip to content

Instantly share code, notes, and snippets.

@bishil06
Created February 18, 2021 21:39
Show Gist options
  • Save bishil06/d78c91cce4038d2df9b9ba58bcb3abfa to your computer and use it in GitHub Desktop.
Save bishil06/d78c91cce4038d2df9b9ba58bcb3abfa to your computer and use it in GitHub Desktop.
_JavaScript_Reverse_Array

JS Reverse Array

let arr1 = Array.from({length: 10000000}, (_, i) => i);

Node version 15.8

  • reverse method 274ms
  • index swap 9ms
  • index swap es6 8ms
let arr1 = Array.from({length: 10000000}, (_, i) => i);
console.log(arr1);
console.time('reverse');
arr1.reverse() // 274
console.timeEnd('reverse');
console.log(arr1);
function rswap(arr) {
let [l, r] = [null, null];
let len = arr.length;
for (l=0, r=len-1; l < r; l +=1, r -=1) {
let temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
return arr;
}
let arr2 = Array.from({length: 10000000}, (_, i) => i);
console.log(arr2);
console.time('temporary swap');
rswap(arr2) // 9ms
console.timeEnd('temporary swap');
console.log(arr2);
function rswap2(arr) {
let [l, r] = [null, null];
let len = arr.length;
for (l=0, r=len-1; l < r; l +=1, r -=1) {
[arr[l], arr[r]] = [arr[r], arr[l]]
}
return arr;
}
let arr3 = Array.from({length: 10000000}, (_, i) => i);
console.log(arr3);
console.time('temporary swap2');
rswap(arr3) // 8ms
console.timeEnd('temporary swap2');
console.log(arr3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment