Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop efficiency

Tags:

javascript

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 ?

like image 735
Misha Moroshko Avatar asked Apr 30 '10 05:04

Misha Moroshko


People also ask

Which loop is more efficient in JavaScript?

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.

Which for loop is most efficient?

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.

Which is more efficient for loop or while loop in JavaScript?

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.

Is for loop faster than Map JavaScript?

Even with these simple tests, loops are almost three times faster.


2 Answers

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)

like image 69
Pascal MARTIN Avatar answered Sep 18 '22 16:09

Pascal MARTIN


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).

like image 26
Ash Avatar answered Sep 21 '22 16:09

Ash