brainmassage
brainmassage

Reputation: 1254

When updating some of the elements in an object array in Javascript, which one is a more efficient way considering the array size?

Consider this very simple js code below:

for(var i = 0; i < rows.length; i++) {
    if(rows[i].index !== i) {
        rows[i].index = i;
    }
}

Say, the length of the array is 8, and it will enter the if block 2 times. Is it better to do this way:

for(var i = 0; i < rows.length; i++) {
    rows[i].index = i;
}

I want to know which one is less costly with large arrays and small arrays; the if block, or the value assign in every cycle of the loop?

Upvotes: 3

Views: 60

Answers (1)

nicfo
nicfo

Reputation: 450

it shouldn't really matter. I still tried it on jsPerf for the sake of curiousity and it seems that the second version is faster.

Upvotes: 1

Related Questions