# Set array length to variable before loops

### # Intro

Somebody may have told you at some point that you need to store array lengths to variables prior to starting a for loop. W3 Schools also provides the same advice with the following code samples:

``````// bad
var i;
for (i = 0; i < arr.length; i++) {

// better
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
``````

The page states that the “better” runs faster.

### # Tests

I ran the following code from the console of Chrome on an `about:blank` page.

#### # Setting variable

``````  let totals = [];
for(let jj = 0; jj < 10000; jj++){
let arr = new Array(10000);
let results = [];
let l = arr.length;
let t0 = performance.now();
for(let i = 0; i < l; i++){
results.push(arr[i]);
}
let t1 = performance.now();
totals.push(t1 - t0);
}

let sum = totals.reduce((s, t)=> s+t, 0);
let avg = sum / totals.length;
console.log(avg);
``````

#### # Using arr.length

``````  let totals = [];
for(let jj = 0; jj < 10000; jj++){
let arr = new Array(10000);
let results = [];
let t0 = performance.now();
for(let i = 0; i < arr.length; i++){
results.push(arr[i]);
}
let t1 = performance.now();
totals.push(t1 - t0);
}

let sum = totals.reduce((s, t)=> s+t, 0);
let avg = sum / totals.length;
console.log(avg);
``````

#### # Results

Method Chrome IE Edge
Setting Variable 0.1556 ms 2.6418 ms 6.3220 ms
Using .length 0.1521 ms 3.0555 ms 6.7389 ms

### # Analysis

It appears that there are environments that optimize the arr.length approach and those that do not. The results from Chrome do not appear to show a significant difference between the two approaches, whereas IE and Edge consistently showed the variable approach to be ever so slightly faster.

It should be noted that the length property does not appear to be a calculated property, and is actually set. Using proxies, we can at least confirm this in Edge and Chrome

``````let proxy = new Proxy([], {
set(obj, key, newVal){
console.log(key, newVal);
obj[key] = newVal;
return true;
}
});
proxy.push("Performant JS");
/* console
0
length 1
*/
``````

Why, then, is there the consistent difference within Internet Explorer and Edge? Perhaps reading object properties takes more time than reading a local variable.

If you find yourself in the position of creating large loops, you should probably favor assigning the variable. Otherwise, stick with the way that you like.

• ## Optional Chaining in JavaScript

TC39 introduced a new proposal for optional chaining in JavaScript addressing a common pain point

• ## Array and Object Serialization & Deserialization

I would love to find a faster way to handle serialization and deserialization of JavaScript objects.

• ## Performance - document.getElementById vs document.querySelector

The introduction of the document.querySelector and document.querySelectorAll functions was a welcome response to jQuery’s use of CSS selectors to select elements.