Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function calling in JavaScript

I know you should tread lightly when making recursive calls to functions in JavaScript because your second call could be up to 10 times slower.

Eloquent JavaScript states:

There is one important problem: In most JavaScript implementations, this second version is about 10 times slow than the first one. In JavaScript, running a simple loop is a lot cheaper than calling a function multiple times.

John Resig even says this is a problem in this post.

My question is: Why is it so inefficient to use recursion? Is it just the way a particular engine is built? Will we ever see a time in JavaScript where this isn't the case?

like image 717
Mike Fielden Avatar asked Aug 17 '11 17:08

Mike Fielden


2 Answers

Function calls are just more expensive than a simple loop due to all the overhead of changing the stack and setting up a new context and so on. In order for recursion to be very efficient, a language has to support some form of tail-call elimination, which basically means transforming certain kinds of recursive functions into loops. Functional languages like OCaml, Haskell and Scheme do this, but no JavaScript implementation I'm aware of does so (it would only be marginally useful unless they all did, so maybe we have a dining philosophers problem).

like image 96
Chuck Avatar answered Nov 20 '22 10:11

Chuck


This is just a way the particular JS engines the browsers use are built, yes. Without tail call elimination, you have to create a new stack frame every time you recurse, whereas with a loop it's just setting the program counter back to the start of it. Scheme, for example, has this as part of the language specification, so you can use recursion in this manner without worrying about performance.

https://bugzilla.mozilla.org/show_bug.cgi?id=445363 indicates progress being made in Firefox (and Brendan Eich speaks in here about it possibly being made a part of the ECMAScript spec), but I don't think any of the current browsers have this implemented quite yet.

like image 45
rwat Avatar answered Nov 20 '22 12:11

rwat