0

I came up with a article which pointed out recursion being much slower than non-recursive approach, when running on AWS Lambda with Node.js https://hackernoon.com/aws-lambda-go-vs-node-js-performance-benchmark-1c8898341982

I was a little interested about this finding and tried to compare these two as well. My findings have been very similar to what this article points out recursion being up to 5 times more slower than for-loop with simple Fibonacci example. https://codesandbox.io/s/y0xvn96xzv

What would be a reason or cause, to this kind of an effect in JavaScript? As well I would gladly hear if there are other similar coincidences when working with JavaScripts call-stack or some general rules what to avoid and what would be an "best practice" to avoid performance issues.

Jimi Pajala
  • 2,358
  • 11
  • 20
  • 2
    Possible duplicate of [Recursion vs loops](https://stackoverflow.com/questions/660337/recursion-vs-loops) – Heretic Monkey Feb 05 '19 at 16:45
  • 1
    Not really a duplicate. Those answers are about the choice between one or the other. This question is asking why one is slower. – Federico klez Culloca Feb 05 '19 at 16:46
  • 1
    @FedericoklezCulloca Then feel free to close as dupe of [Is iteration faster than recursion, or just less prone to stack overflows?](https://stackoverflow.com/q/9474465/215552) or [Is recursion ever faster than looping?](https://stackoverflow.com/q/2651112/215552) or [Recursion or Iteration?](https://stackoverflow.com/q/72209/215552)... – Heretic Monkey Feb 05 '19 at 17:14

1 Answers1

2

Recursion is often slower than iteration because you have to manage the call stack frame in addition to managing the looping content. So at the end, more code will be run.

jo_va
  • 13,504
  • 3
  • 23
  • 47