Skip to content

Instantly share code, notes, and snippets.

@vanowm
Last active June 30, 2024 00:22
Show Gist options
  • Save vanowm/52f84c5cfe44859b4bcba661ea3dd254 to your computer and use it in GitHub Desktop.
Save vanowm/52f84c5cfe44859b4bcba661ea3dd254 to your computer and use it in GitHub Desktop.
Fill an array with consecutive numbers (https://jsbench.github.io/#52f84c5cfe44859b4bcba661ea3dd254) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Fill an array with consecutive numbers</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
suite.add("base https://stackoverflow.com/questions/55579499", function () {
// base https://stackoverflow.com/questions/55579499
var n=1000;
var arr=[n];
for (i=n;i>=0;i--) {
arr[i]=i;
}
});
suite.add("for loop", function () {
//for loop
const arr = Array(1000);
for(let i = 0; i < arr.length; i++)
arr[i] = i;
});
suite.add("while loop", function () {
//while loop
let i = 1000;
const arr = Array(i);
while (i) {
arr[--i] = i;
}
});
suite.add("Array.from", function () {
//Array.from
const arr = Array.from(Array(1000).keys());
});
suite.add("Array.from w/callback", function () {
//Array.from w/callback
const arr = Array.from({length:1000},(e,i)=>i)
});
suite.add("Array.fill.map", function () {
//Array.fill.map
const arr = Array(1000).fill().map((_, i) => i);
});
suite.add("[...keys]", function () {
//[...keys]
const arr = [...Array(1000).keys()]
});
suite.add("[...].map", function () {
//[...].map
const arr = [...Array(1000)].map((a,b)=>b)
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("Fill an array with consecutive numbers");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment