What are the pros and cons to assigning the end point of a for loop?

被刻印的时光 ゝ 提交于 2019-12-13 02:58:40

问题


In various languages (I'm going to use JavaScript here, but I've seen it done in PHP and C++ and probably elsewhere), there seem to be a couple of ways of constructing a simple for loop. Version 1 is like:

var top = document.getElementsByTagName("p"); 
for (var i = 0; i < top.length; i++) {
...do something
}

Whereas elsewhere I've seen people construct the for loop like:

for (var i = 0, ii = top.length; i < ii; i++) 

It seems like people do it without rhyme or reason - the same programmer will do both in the same script. Is there any reason to do one and not the other?

Cheers


回答1:


In some languages, getting the length of an array or string may be an expensive operation. Since it doesn't change during the loop, doing it every time you test whether the iteration variable has reached the end is wasteful. So it's more efficient to get the length once and save it in a variable.

An example would be iterating over a string in C. In C, strlen() is an O(n) operation, because it has to search the char array looking for the terminating 0 element. If you wrote:

for (i = 0; i < strlen(string); i++)

your loop would be O(n2).

In languages like Javascript, getting the length is inexpensive, but programmers stick with their old habits. And programmers who have never even used those other languages learn idioms from the ones who did, so they use this coding style without even knowing the reason.

See this YouTube video for an explanation of how this type of thing happens in communities:

https://www.youtube.com/watch?v=b4vJ8l2NfIM



来源:https://stackoverflow.com/questions/25460123/what-are-the-pros-and-cons-to-assigning-the-end-point-of-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!