Jimi Pajala
Jimi Pajala

Reputation: 2378

Why recursion seems to be much slower than for-loop in JavaScript?

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.

Upvotes: 0

Views: 261

Answers (1)

jo_va
jo_va

Reputation: 13983

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.

Upvotes: 2

Related Questions