3

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?

asked Feb 5, 2016 at 10:46
2
  • 2
    I would say the version without the if , but you should test it on jsperf Commented Feb 5, 2016 at 10:51
  • 1
    There's only one way to find out: measure it. But you should not care, and go for the simpler one. Commented Feb 5, 2016 at 10:57

1 Answer 1

1

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.

answered Feb 5, 2016 at 11:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.