Why Object of Arrays (SoA pattern) beat interleaved arrays: a JavaScript performance rabbit hole

24 points by aapoalas


alexjurkiewicz

As you figured out, the cost of for-loop iterations dominates this microbenchmark. You can massively improve performance by using a while-loop instead:

    let sumInterleavedWhile = 0;
    const startInterleavedWhile = performance.now();
    for (let iter = 0; iter < 10; iter++) {
        let i = 0;
        while (i < ARRAY_SIZE) {
            sumInterleavedWhile +=
                interleaved[i] +
                interleaved[i + 1] +
                interleaved[i + 2];
            i += 3;
        }
    }
    const timeInterleavedWhile = performance.now() - startInterleavedWhile;

This trick also significantly speeds up the SoA approach (but not AoS):

❯ node main.js
AoS:         745.95ms
AoS (while): 748.82ms
SoA:         427.49ms
SoA (while): 411.45ms
Interleaved: 662.16ms
Interleaved (while): 185.67ms