Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
ajax333221 Avatar asked Dec 09 '11 22:12

ajax333221


People also ask

How can use length of array in for loop?

As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0). Using this loop you can search if a specific value is present in the array or not.

What determines the length of an array?

The simplest procedural way to get the value of the length of an array is by using the sizeof operator. First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

How does array length property work?

When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements. Thus, the length property does not necessarily indicate the number of defined values in the array.

Is getting length of array constant time?

It is a constant time operation in all of JAVA implementations because JVM has to store this field to check index (it has to throw IndexOutOfBoundsException if index is invalid ).


1 Answers

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++; } 
like image 157
Rob W Avatar answered Oct 16 '22 07:10

Rob W