Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster in Javascript? A loop or repeated function call?

Which of these two bits executes (counts) faster?

var i = 0;
while(true){
    i++;
}

or

var i = 0;
inc = function(){
    i++;
    inc();
}

Does the preferred way change if the looped code / function gets longer?

like image 455
Balz Guenat Avatar asked Feb 17 '26 01:02

Balz Guenat


2 Answers

This will only give you a stack overflow as there is no end condition for the recursion :

var i = 0;
inc = function(){
    i++;
    inc();
}

For a great enough i, this will fail faster than a standard loop would do.

More generally, there is greater overhead in calling a function than just looping. Make a function when it helps your code being reusable, or readable. A loop is fast.

like image 78
Denys Séguret Avatar answered Feb 18 '26 14:02

Denys Séguret


If you have very few iterations, it doesn't matter much. There is more overhead in calling a function, but that doesn't make a big difference for a short loop.

The second method is limited by the stack size. If you have too many iterations, it will run out of stack space and crash.

So, the first method will run faster, but the entire question is moot as the second method is in big risk of crashing in a loop that is long enough that the speed makes a difference.

like image 25
Guffa Avatar answered Feb 18 '26 13:02

Guffa