Benchmarking Array iteration in Javascript

Published

After writing my article on flattening arrays in Unity C#, I was wondering how much performance was gained by using flattened 1D array instead of 2D arrays in javascript.

The answer is: 1D array are about 20% faster than 2D array.

For good measure I also tried other indexing methods but a simple double loop seems to be performing the best among all other methods.

Benchmarks are available on jsbench: https://jsben.ch/W3X2h

Here’s the best performing code on a 1D bool array. Nothing fancy done here.

const width = 1000;
const height = 1000;

const arr = Array.from({length: width * height}, () => Math.random() > 0.5);


let dsmth;
for (let i = 0; i < width; i++) {
  	for (let j = 0; j < height; j++) {
  	dsmth = arr[i + j * width];
	}
}