State the difference - Recursion vs iteration performance in java

403    Asked by HarryButler in Java , Asked on Oct 13, 2022

 I have read recently some articles (e.g. http://dailyjs.com/2012/09/14/functional-programming/) about the functional aspects of Javascript and the relationship between Scheme and Javascript (the latter was influenced by the first, which is a functional language, while the O-O aspects are inherited from Self which is a prototyping-based language).


However my question is more specific: I was wondering if there are metrics about the performance of recursion vs. iteration in Javascript.


I know that in some languages (where design iteration performs better) the difference is minimal because the interpreter / compiler converts recursion into iteration, however I guess that probably this is not the case of Javascript since it is, at least partially, a functional language.


Answered by Rachel Kerr

Recursion vs iteration performance


JavaScript does not perform tail recursion optimization, so if your recursion is too deep, you may get a call stack overflow. Iteration doesn't have such issues. If you think you are going to recurse too much, and you really need recursion (for example, to do flood-fill), replace the recursion with your own stack.

Recursion performance is probably worse than iteration performance, because function calls and returns require state preservation and restoration, while iteration simply jumps to another point in a function.



Your Answer

Interviews

Parent Categories