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
Written by Esteban
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#