SoFunction
Updated on 2025-04-10

Does the length value need to be cached in the for loop

I believe many programmers have been confused about whether the length value needs to be cached in the for loop. Please see the following for analysis of this issue:

In JS performance optimization, there is a common small optimization, i.e.

// No cachefor (var i = 0; i < ; i++) {
...
}

// cachevar len = ;
for (var i = 0; i < len; i++) {
...
}

So, should we abandon this writing method? No, there is another situation where this writing method must be used.

Please see the example:

Copy the codeThe code is as follows:

var divs = ("div"), i, div ;
for( i=0; i<; i++ ){
div = ("div");
    ("div");
}

The above code will cause an infinite loop: the first line of code will get the nodelist of all div elements. Since the nodelist is dynamic, as long as a new div is added to the page, the next for loop will evaluate again, so i and each time will be incremented at the same time, and their values ​​will never be equal, creating a dead loop.

So, if you want to iterate over a nodelist, it is best to initialize the second variable using the length attribute, and then compare the iterator with the variable. The modified code is as follows:

Copy the codeThe code is as follows:

var divs = ("div"), i, div ,len ;
for(i=0;len=;i<len;i++){
div = ("div");
("div");
}

In this example, len is initialized. Since len holds a snapshot at the beginning of the loop, the infinite loop problem that occurred in the previous example will be avoided. Therefore, when it is necessary to loop iteration on nodelist, it is safer to use this method.

Summarize:
1. Whether cached length value is conducive to performance optimization is a matter that needs to be judged based on the specific situation. Generally speaking, it is still beneficial to reduce access to DOM;
2. When you need to operate nodelist, it is recommended to cache the value of length to avoid a dead loop.

The above content is a complete introduction to whether the length value needs to be cached in the for loop. I hope you like it.