开发者

best way to loop an array [closed]

As it currently stands, this question is not a good fit for our Q&am开发者_开发问答p;A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.
var data = [];

for (i = 0, len = data.length; i < len; i++) {

for (i = 0, i < data.length; i++) {

What is the difference between these two way of forming an loop and which is sited as best among them.

Calling the first one is cheaper than the second one. Is it true?


Yes, it is - according to:

http://blogs.oracle.com/greimer/entry/best_way_to_code_a

Note: you could easily build a test if you are not convinced.


In the first case, you'll have an additional len variable the holds data.length. You can do this if you need the value of data.length again inside the for loop (f.e. if retrieving it is computionally expensive).

But note that it is the same as

len = data.length;
for (i = 0; i < len; i++) {

which I'd prefer for readability.


It strongly depends of the language. Most compilers will see length to be a loop invariant and move it outside itself. This kind of details are of little importance, the real important thing in loop is to have loops that are cache friendly , ie go down your data in a way cache spatial and temporal locality is maximal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜