分配for循环的终点有什么优点和缺点? [英] What are the pros and cons to assigning the end point of a for loop?

查看:163
本文介绍了分配for循环的终点有什么优点和缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在各种语言(我将在这里使用JavaScript,但我已经看到它在PHP和C + +和其他地方完成),似乎有几种方法来构造一个简单的for循环。版本1如下:

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
}

而在其他地方我已经看到人们构建的for循环像:

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?

干杯

推荐答案

在某些语言中,数组或字符串可能是一个昂贵的操作。因为它在循环期间不改变,所以每次测试迭代变量是否到达结束都是浪费。因此,获取长度一次并将其保存在变量中会更有效。

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.

一个例子是对C中的字符串进行迭代。在C中, strlen()是一个O(n)操作,因为它必须搜索char数组寻找termination 0元素。如果你写了:

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++)

您的循环将是O(n 2 )。

your loop would be O(n2).

在像Javascript这样的语言中,获取长度是便宜的,但程序员坚持他们的旧习惯。而且从来没有使用过这些其他语言的程序员从中学习成语,所以他们使用这种编码风格,甚至不知道原因。

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.

查看此YouTube视频这种类型的事件在社群中发生的解释:

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

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

这篇关于分配for循环的终点有什么优点和缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆