Skip to content

Instantly share code, notes, and snippets.

@felipec
Last active August 16, 2025 20:43
Show Gist options
  • Select an option

  • Save felipec/804a3b61b5f1074a55f820cf696e3cd8 to your computer and use it in GitHub Desktop.

Select an option

Save felipec/804a3b61b5f1074a55f820cf696e3cd8 to your computer and use it in GitHub Desktop.
Benchmark for Array.from
const N = 1_000_000;
function map(a, cb) {
const r = Array(a.length);
for (let i = 0; i < a.length; i++)
r[i] = cb(a[i]);
return r;
}
const cb = v => v ** 2;
const funcs = {
'Array.map()': x => x.map(cb),
'map()': x => map(x, cb),
'Array..fill()': x => Array(N).fill().map((_,i) => cb(x[i])),
'Array.from()': x => Array.from(x, cb),
'index: Array.from()': _ => Array.from({length: N}, (_, i) => i),
'index: Array()..fill()': _ => Array(N).fill().map((_, i) => i),
'empty: Array()': _ => Array(N),
'empty: Array.from()': _ => Array.from({length:N}),
'empty: Array()..fill()': _ => Array(N).fill(),
};
const data = Array.from({length:N}, _ => Math.random());
for (const [n,f] of Object.entries(funcs)) {
f(data); // warmup
const start = performance.now();
f(data);
f(data);
f(data);
const end = performance.now();
console.log(`${n}: ${end - start}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment