Whether the length value needs to be cached in the for loop, I believe many programmers have struggled with this issue. Please see below for the analysis of this issue:
In JS performance optimization, there is a common small optimization, which is
// 不缓存 for (var i = 0; i < arr.length; i++) { ... } // 缓存 var len = arr.length; for (var i = 0; i < len; i++) { ... }
So, should we abandon this way of writing? No, there is another situation where this way of writing must be used.
Please see the example:
The above code will cause an infinite loop: the first line of code will obtain 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 update the divs again. .length is evaluated, so i and divs.length will be incremented at the same time each time. As a result, their values will never be equal, creating an infinite loop.
So, if you want to iterate 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:
In this example, len is initialized. Since len stores a snapshot of divs.length at the beginning of the loop, it will avoid the infinite loop problem that occurred in the previous example. Therefore, when it is necessary to loop iterate nodelist, It is safer to use this method.
Summary:
1. Whether caching the length value is beneficial to performance optimization is a matter that needs to be judged based on the specific situation. Generally speaking, reducing access to the DOM is still beneficial;
2. When you need to operate nodelist, it is recommended to cache the length value to avoid an infinite loop.
The above content is the complete introduction to whether the length value needs to be cached in the for loop. I hope you like it.