Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - Do loops check the array.length every time when comparing i against array.length?

I was browsing around and I found this:

var i, len;
for(i = 0, len = array.length; i < len; i++) {  
   //...
}

My first thoughts are:

  • Why he did that? (it must be better for some reason)
  • Is it worth it? (I assume yes, why else he will do it this way?)

Do normal loops (the ones that don't cache the length) check the array.length each time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A loop consisting of three parts is executed as follows:

for (A; B; C)

A - Executed before the enumeration
B - condition to test
C - expression after each enumeration (so, not if B evaluated to false)

So, yes: The .length property of an array is checked at each enumeration if it's constructed as for(var i=0; i<array.length; i++). For micro-optimisation, it's efficient to store the length of an array in a temporary variable (see also: What's the fastest way to loop through an array in JavaScript?).

Equivalent to for (var i=0; i<array.length; i++) { ... }:

var i = 0;
while (i < array.length) {
    ...
    i++;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...