JS: Speed Comparison of Generating Array

By Xah Lee. Date: .

Speed Comparison of Generating Array

/*

bench.js
2023-10-20
comparing speed of generating array

*/

const f1 = (x) => {
  const rr = Array(x);
  let i = 0;
  while (i < x) rr[i] = ++i;
  return rr;
};

const f2 = ((x) => {
  const rr = [];
  for (let i = 1; i <= x; i++) rr.push(i);
  return rr;
});

const f3 = ((max) => (Array(max).fill(1).map((x, i) => (x + i))));

// HHHH---------------------------------------------------

// check if same output
console.log(f1(6));
console.log(f2(6));
console.log(f3(6));

// HHHH---------------------------------------------------

// bench
Deno.bench("loop direct assign", () => {
  f1(10_000);
});

Deno.bench("loop with push", () => {
  f2(10_000);
});

Deno.bench("array fill", () => {
  f3(10_000);
});

shell output:

js deno bench 2023-10-20 V99j
js deno bench 2023-10-20 V99j

JavaScript, Speed Comparison