问题
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