0

I'm developping an application that needs a lot of arithmetic optimizations and I've just found out that accessing an array with arrow functions was faster than with brackets. Can someone explain why? The arrow function adds a step, so logically it should be slower.

I added a snippet with my benchmark. Focus on the two first lines of each test (array[i] and lambda(i)). The gain of speed is around 30% on Google Chrome. It's much smaller with Firefox (2%?) however. I repeated these results a lot of time...

Thank you for your answer.

const l = 1e3;
const n = 512 * 512;

const array = new Float32Array(n)
for (let i = 0; i < n; i++)
    array[i] = Math.random();

array.get = function (i) {
    return this[i];
};

const lambda = i => array[i];

class Float32ArrayLike extends Float32Array {
    get(i) {
        return this[i];
    }
}


const arrayLike = new Float32ArrayLike(n);
for (let i = 0; i < n; i++)
    arrayLike[i] = array[i];

for (let r = 0; r < 2; r++) {
    console.log("test", r)

    let t0, s;

    t0 = performance.now();
    s = 0;
    for (let i = 0; i < l; i++)
        for (let i = 0; i < n; i++)
            s += array[i];
    console.log("array[i]        ", Math.round(performance.now() - t0), "ms")

    t0 = performance.now();
    s = 0;
    for (let i = 0; i < l; i++)
        for (let i = 0; i < n; i++)
            s += lambda(i);
    console.log("lambda(i)       ", Math.round(performance.now() - t0), "ms")

    t0 = performance.now();
    s = 0;
    for (let i = 0; i < l; i++)
        for (let i = 0; i < n; i++)
            s += array.get(i);
    console.log("array.get(i)    ", Math.round(performance.now() - t0), "ms")

    t0 = performance.now();
    s = 0;
    for (let i = 0; i < l; i++)
        for (let i = 0; i < n; i++)
            s += arrayLike.get(i);
    console.log("arrayLike.get(i)", Math.round(performance.now() - t0), "ms")

}
  • Do you mean that `s += lambda(i);` is faster than `s += array[i];`? If you run your tests a few thousand times, what is the average time for each test? And how much do the tests differ? – Some programmer dude Jul 22 '22 at 11:33
  • 1
    FF 102: `array[i]: 653ms; lambda(i): 670ms` – Justinas Jul 22 '22 at 11:36
  • I tested the snippet with him (colleague here). I get `array[i]: 223 ms; lambda(i): 183 ms` right now on the 2nd test on Chrome. We have found even bigger gaps on his computer. – Alexandre Huat Jul 22 '22 at 12:36
  • 1
    [Don't use non-idiomatic code to improve performance](https://stackoverflow.com/a/60635905/1048572)! As for why you got weird results, read https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html. – Bergi Jul 22 '22 at 12:51

0 Answers0