+ 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
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.
+ 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.
+ 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 ;))
+ 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?