DEV Community

Discussion on: Why is using javascript “for loop” for array iteration a bad idea?

Collapse
 
peerreynders profile image
peerreynders • Edited
const length = 1000000;

let start = performance.now();
const a = new Array(length);
let finish = performance.now();
console.log(`Sparse array was created in ${finish - start}ms`); // < 5ms

start = performance.now();
const b = Array.from({ length });
finish = performance.now();
console.log(`Dense array was created in ${finish - start}ms`); // ~60ms

start = performance.now();
const c = [];
c[length - 1] = 1;
finish = performance.now();
console.log(`Element added in ${finish - start}ms`); // < 1ms
console.log(c[length - 1]); // 1
console.log(c.length); // 1000000
Enter fullscreen mode Exit fullscreen mode

Basically think of arrays as key-value stores that use positive integers as keys.


The problem is that JavaScript engines optimize arrays for performance

v8.dev: Elements kinds in V8:

  • Small Integers: PACKED_SMI_ELEMENTS -> HOLEY_SMI_ELEMENTS
  • Doubles: PACKED_DOUBLE_ELEMENTS -> HOLEY_DOUBLE_ELEMENTS
  • Other: PACKED_ELEMENTS -> HOLEY_ELEMENTS .
  • PACKED (dense) arrays can transition to HOLEY (sparse) arrays - but not the other way around
  • PACKED processing is more optimized, though:

the performance difference between accessing holey or packed arrays is usually too small to matter or even be measurable.

That said (as already suggested elsewhere), if holes don't have any particular meaning within the processing context, it's better to sanitize HOLEY arrays into PACKED arrays rather than relying on the "skipping behaviour" of select methods.