JS: Speed Comparison, Array Push vs Unshift
Speed comparison: array push vs unshift
this shows, Array.prototype.push is a magnitude faster than Array.prototype.unshift, even if you reverse the whole array at the end.
// bench039.js // 2022-08-27 // comparing speed array methods push vs unshift const f_push = ((x) => { const xar = []; for (let i = 0; i < x; i++) xar.push(i); return xar.reverse(); }); const f_unshift = ((x) => { const xar = []; for (let i = 0; i < x; i++) xar.unshift(i); return xar; }); console.log(f_push(10)); console.log(f_unshift(10)); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] Deno.bench("f_push", () => { f_push(10_000); }); Deno.bench("f_unshift", () => { f_unshift(10_000); }); /* [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] cpu: AMD Ryzen 5 3600 6-Core Processor runtime: deno 1.22.3 (x86_64-pc-windows-msvc) file:///C:/Users/xah/.emacs.d/temp/x20220828_0934_fe7.js benchmark time (avg) (min … max) p75 p99 p995 ------------------------------------------------- ----------------------------- f_push 44.16 µs/iter (40.8 µs … 193.1 µs) 41.5 µs 99.1 µs 100.5 µs f_unshift 3.92 ms/iter (3.89 ms … 4.1 ms) 3.93 ms 4.06 ms 4.1 ms */