Is
for (var i=0, cols=columns.length; i<cols; i++) { ... }
more efficient than
for (var i=0; i<columns.length; i++) { ... }
?
In the second variant, is columns.length
calculated each time the condition i<columns.length
is checked ?
forEach() loop: Each element of the array is subjected to a function performing some operation or task. The function is specified as a parameter of the forEach method in JavaScript. It performs highly efficient tasks where functional code is required.
Repeat keeps iterating until a condition is false, whereas a while loop is the opposite. Pros: It turns out that Repeat is actually quite a bit more efficient than While, demonstrated below. Repeat may have the convenience that in many situations, the condition is not known or even defined until inside the loop.
Result. I have perform around 10 test and got conclude that while loop is faster then for loop if we are comparing very high iteration execution. for smaller iteration up to 10⁴ both perform nearly same. We observe that while loop take almost double time then for loop.
Even with these simple tests, loops are almost three times faster.
Any expression that's in the second portion of a for will be evaluated once per loop.
So, here, with your second proposition, yes, columns.length
will be calculated each time the condition is checked -- which would make the first proposition faster than the second one.
(That's true for many other languages, btw)
Micro optimizations like this don't make huge sense in a language like Javascript unless you have tested and found the loop performance to be an issue.
However, columns.length must be evaluated on each iteration because the number of columns may change during a loop iteration. Therefore storing the loop limit may give slightly better performance (but see my first point).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With