Skip to content

Instantly share code, notes, and snippets.

@korzo
Last active July 8, 2022 17:21
Show Gist options
  • Save korzo/546df78d4fd6ca82a03c9ea71f7c49c3 to your computer and use it in GitHub Desktop.
Save korzo/546df78d4fd6ca82a03c9ea71f7c49c3 to your computer and use it in GitHub Desktop.
Reverse array benchmark
// npm i benchmark microtime
//
// https://jsben.ch/QlNfk
const suite = new (require("benchmark").Suite)();
const limit = 1000;
suite
.add("reverse", function () {
const arr = [];
for (var i = 0; i <= limit; i++) {
arr.push(i);
}
const res = arr.reverse();
console.assert(res[0] === limit);
})
.add("loop", function () {
const arr = [];
for (var i = 0; i <= limit; i++) {
arr.push(i);
}
const res = [];
for (var j = arr.length - 1; j >= 0; --j) {
res.push(arr[j]);
}
console.assert(res[0] === limit);
})
.add("unshift", function () {
const arr = [];
for (var i = 0; i <= limit; i++) {
arr.unshift(i);
}
console.assert(arr[0] === limit);
})
.add("concat", function () {
let arr = [];
for (var i = 0; i <= limit; i++) {
arr = [i].concat(arr);
}
console.assert(arr[0] === limit);
})
.add("spread", function () {
let arr = [];
for (var i = 0; i <= limit; i++) {
arr = [i, ...arr];
}
console.assert(arr[0] === limit);
})
.on("cycle", function (event) {
console.log(String(event.target));
})
.on("complete", function () {
console.log("Fastest is " + this.filter("fastest").map("name"));
})
// run async
.run({ async: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment