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")
}