rsm rsm - 5 months ago 9
Javascript Question

are attributes called multiple times at the conditon of for loops?

A programmer told me that when codding loops if an attribute is added at the condition of for loops, it will be calculated at each iteration. Ex:

var elements=['a','b','c','d'] // imagine a very long list

for (var i=0; i < elements.length; i++) { // <- Here is array.length being called
var element = elements[i]
}


In this case, if what he told me is true:
elements.length
would be called at each iteration in order to calculate the condition.

To optimize the code I'll think in doing:

var elements=['a','b','c','d'] // imagine a very long list
var elements_length=elements.length

for (var i=0; i < elements_length; i++) { // <- Here is array.length being called
var element = elements[i]
}


And probably this can not even noticed with small lists.

Is all this true? Is there any way of checking this? Probably this can be checked with a timer, but I was wondering if this is a known behavior.

Answer

Yes it is true. Here is a diagnosis:

Here is the data access time for variables and object properties:

The important lesson to take from this information is to always store frequently accessed values in a local variable. Consider the following code:

function process(data){
    if (data.count > 0){
        for (var i=0; i < data.count; i++){
            processData(data.item[i]);
        }
    }
}

This snippet accesses the value of data.count multiple times. At first glance, it looks like this value is used twice: once in the if statement and once in the for loop. In reality, though, data.count is accessed data.count plus 1 times in this function, since the control statement (i < data.count) is executed each time through the loop. The function will run faster if this value is stored in a local variable and then accessed from there:

function process(data){
    var count = data.count;
    if (count > 0){
        for (var i=0; i < count; i++){

            processData(data.item[i]);
        }
    }
}

Source: Writing Efficient JavaScript