Last Updated: May 21, 2016
·
1.345K
· fr0gs

Javascript Array length performance comparison

By caching the length of array's length we can save up in some times quite a lot of miliseconds. This is useful specially in cases where algorithm performance is critical.

var l = [];
for (let i=0; i<10000; i++) {
    l.push(i);
}
let start = performance.now();

// no length caching
for (let j=0; j<l.length; j++) {
    l[j] += 1; // simple
}

let end = performance.now();
let total = end-start;
console.log(total);

//caching length

start = performance.now();
for (let j=0, x = l.length; j<x; j++) {
    l[j] += 1; // simple
}
end = performance.now();
total = end-start;
console.log(total);

First measure and second measure:
0.6850000000001728 0.2849999999998545