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?
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?
Share Improve this question edited Jul 15, 2013 at 12:36 holographic-principle 19.7k10 gold badges48 silver badges62 bronze badges asked Aug 20, 2012 at 11:27 Balz GuenatBalz Guenat 1,7215 gold badges17 silver badges37 bronze badges 4-
1
Try both methods with a large value for
i
. – Oded Commented Aug 20, 2012 at 11:29 - 1 The second one isn't simply repeated, it's recursive. And never ending (I mean, until stack overflow). And insane. – Denys Séguret Commented Aug 20, 2012 at 11:29
- JSPerf can easily help you with this: jsperf./factorial-recursive-vs-not-recursive. – VisioN Commented Aug 20, 2012 at 11:29
-
1
Whenever the question is like
who's faster, A or B
, the only real answer is to setup a benchmark and test them for yourself. – Michael Berkowski Commented Aug 20, 2012 at 11:29
2 Answers
Reset to default 7This 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.
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.