+ 5

Is recursion advisable on JavaScript or is a better approch iterations?

I know that the recursion has its limits, but within reason is better to use it instead of iterations, or undergo performance vs using iterations. What do you think about it

25th Jul 2017, 7:52 PM
AldoS
AldoS - avatar
4 Respostas
+ 3
Overall recursion is worse than iterations in terms of performance because a recursive function needs to backtrack the stack to get the previous values. This quickly causes stack overflow leading to crashes. It would be better in my opinion to use iterations because the browser itself uses a lot of RAM, so you don't want a recursive function using up a lot of memory.
25th Jul 2017, 8:19 PM
Hassie
Hassie - avatar
+ 3
According to lots of things I'm finding online Javascript does not optimize tail recursion. So, I suppose itterations are (far) faster. However EVERYTHING I was looking at could be out dated. (Whether or not it has changed, I don't know). Just know that even though it could be a bit slower, it could be better for read-ability under some circumstances.
25th Jul 2017, 8:21 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
I'm agree with @Hassie: Recursive functions are not well suited in almost of case, because memory use expensive... (and so time expensive). However, in almost of case too, this doesn't make big differences at execution, until you use it with intensive data computation/handling ^^ Anyway, the general rule to follow is quite simple: if you can use simple iteration instead recursion, do it (almost if you need improved performances)... but in some cases, recursion should be the best suited way (better algoritm, good suited data as low data usage... each case is specific by itself ;))
26th Jul 2017, 6:03 AM
visph
visph - avatar
+ 2
Recursion is awesome because of reusibility of code. Iterations can help performance in some situations but in those cases maybe web assembly will take over?
25th Jul 2017, 8:18 PM
Eli Dwor
Eli Dwor - avatar