Home  >  Article  >  Web Front-end  >  Does the length value need to be cached in the for loop_javascript tips

Does the length value need to be cached in the for loop_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:48:411990browse

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:

Copy code The code is as follows:

var divs = document.getElementsByTagName("div"), i, div ;
for( i=0; i div = document.createElement("div");
​ document.body.appendChild("div");
}

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:

Copy code The code is as follows:

var divs = document.getElementsByTagName("div"), i, div ,len ;
for(i=0;len=divs.length;i div = document.createElement("div");
​document.body.appendChild("div");
}

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn