If you need to cache length values in the For loop, I believe a lot of programs apes have struggled with this issue, and here's an analysis of this issue:
In JS performance optimization, there is a common small optimization, that is
Do not cache for
(var i = 0; i < arr.length i++) {
...
}
Cache
var len = arr.length;
for (var i = 0; i < len; i++) {
...
}
So, should we abandon this type of writing? No, there is another situation that must be used.
Take a look at the example:
Copy Code code as follows:
var divs = document.getelementsbytagname ("div"), I, Div;
For (i=0 i<divs.length; i++) {
div = document.createelement ("div");
Document.body.appendChild ("div");
}
The above code leads to an infinite loop: The first line of code gets all the nodelist of the DIV element, because the nodelist is dynamic, so whenever a new div is added to the page, The next for loop evaluates the divs.length again, so I and divs.length increment each time, and their values never equal, creating a dead loop.
So, if you want to iterate over a nodelist it is best to initialize the second variable with the Length property, and then compare the iterator with the variable, and the modified code is as follows:
Copy Code code as follows:
var divs = document.getelementsbytagname ("div"), I, Div, Len;
for (i=0;len=divs.length;i<len;i++) {
div = document.createelement ("div");
Document.body.appendChild ("div");
}
In this example, Len is initialized, and since Len holds a snapshot of the divs.length at the beginning of the loop, it avoids the infinite loop problem that occurs in the previous example, so it is safer to use this method when iterating over NodeList is needed.
Summarize:
1. The value of the length of the cache, whether it is conducive to performance optimization, is a need to judge according to the specific circumstances of the matter, generally speaking, to reduce access to the DOM is still good;
2. When Operation NodeList is required, it is recommended that the value of length be cached to avoid a dead loop.
The above content is for the need to cache the length value in the For loop all the introduction, I hope you like.