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
-
2I would say the version without the if , but you should test it on jsperfmaioman– maioman2016年02月05日 10:51:46 +00:00Commented Feb 5, 2016 at 10:51
-
1There's only one way to find out: measure it. But you should not care, and go for the simpler one.Bergi– Bergi2016年02月05日 10:57:59 +00:00Commented Feb 5, 2016 at 10:57
1 Answer 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.
lang-js