TypedArray vs. array[] vs. nested[][]

Benchmark created on


Description

Guarded read access speed for different array containers.

Setup

var W = 100;
var size = W * W;
var typed = new Int32Array(size);
crypto.getRandomValues(typed);
var array = [...typed];
var nested = [];
for (let n = 0; n < W; n++) {
  nested.push(
    [...typed.slice(n * W, (n + 1) * W)]
    .map(i32 => [i32 & 0xFFFF, i32 >>> 16])
  );
}
var acc = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
typed array (raw)
for (let x = 0; x < size; x++) {
  acc += typed[x];
}
ready
typed array (default)
let idx = 0;
for (let x = 0; x < size; x++) {
  idx = typed[idx] ?? x;
  acc += idx;
}
ready
typed array (guarded)
let idx = 0;
for (let x = 0; x < size; x++) {
  idx = 0 <= idx && idx < size
    ? typed[idx] : x;
  acc += idx;
}
ready
array (raw)
for (let x = 0; x < size; x++) {
  acc += array[x];
}
ready
array (default)
let idx = 0;
for (let x = 0; x < size; x++) {
  idx = array[idx] ?? x;
  acc += idx;
}
ready
array (guarded)
let idx = 0;
for (let x = 0; x < size; x++) {
  idx = 0 <= idx && idx < size
    ? array[idx] : x;
  acc += idx;
}
ready
nested (raw)
for (let y = 0; y < W; y++) {
  for (let x = 0; x < W; x++) {
    acc += nested[y][x];
  }
}
ready
nested (default)
let [a, b] = [0, 0];
for (let y = 0; y < W; y++) {
  for (let x = 0; x < W; x++) {
    [a, b] = nested[b]?.[a] ?? [x, y];
    acc += a + b;
  }
}
ready
nested (guarded)
let [a, b] = [0, 0];
for (let y = 0; y < W; y++) {
  for (let x = 0; x < W; x++) {
    [a, b] = 0 <= a && a < W
      && 0 <= b && b < W
      ? nested[b][a] : [x, y];
    acc += a + b;
  }
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.