This article mainly introduces whether the length value needs to be cached in the for loop. If you need it, you can refer to whether the length value needs to be cached in the for loop, I believe many programmers have struggled with this issue. The following is 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 discard this writing? No, there is another situation where this method must be used.
See the example below:
The Code is as follows:
Var ps = document. getElementsByTagName ("p"), I, p;
For (I = 0; I P = document. createElement ("p ");
Document. body. appendChild ("p ");
}
The above code will lead to an infinite loop: the first line of code will get the nodelist of all p elements. Since nodelist is dynamic, as long as a new p is added to the page, the next for Loop will be directed to ps again. length, So I and ps. length increases at the same time, and their values are never equal. an endless loop is created.
Therefore, if you want to iterate A nodelist, it is best to use the length attribute to initialize the second variable, and then compare the iterator with the variable. The modified code is as follows:
The Code is as follows:
Var ps = document. getElementsByTagName ("p"), I, p, len;
For (I = 0; len = ps. length; I P = document. createElement ("p ");
Document. body. appendChild ("p ");
}
In this example, len is initialized because ps is stored in len. length is a snapshot at the beginning of the loop, so it will avoid the infinite loop problem in the previous example. Therefore, it is safer to use this method when performing loop iteration on nodelist.
Summary:
1. cache the length value to determine whether it is conducive to performance optimization. In general, it is good to reduce DOM access;
2. When nodelist needs to be operated, it is recommended that the length value be cached to avoid endless loops.
The preceding content describes whether to cache the length value in the for loop.