Problem --> Don't Blow Your Stack - Recursion and Trampolines in JavaScript

36 views
Skip to first unread message

Narendra Sisodiya

unread,
Jul 9, 2014, 4:25:45 AM7/9/14
to js-drip-d...@googlegroups.com
trampoline(isEvenInner, 99999);
// => false

trampoline(isEvenInner, 99998);
// => true

Yes, You can avoid Stack Error using trampoline function but that do not solve the problem !

If you make a recursion function, JavaScript makes a Stack!
But If you make a trampoline approach, same number of stack will be there in form of Clousure Stack.
So, execution and memory wise, there is no significant change as such.
This is what I believe.




--
Narendra Sisodiya
UI Architect @
Unicommerce
Delhi - Bharat (India)

Narendra Sisodiya

unread,
Jul 9, 2014, 5:17:05 AM7/9/14
to js-drip-d...@googlegroups.com
From this blog - http://taylodl.wordpress.com/2013/06/07/functional-javascript-tail-call-optimization-and-trampolines/

Why does a trampoline not improve performance? A couple of observations should be made about this trampoline implementation:

  • The number of function invocations is not reduced. The trampoline implementation has essentially the same number of function invocations as the traditional recursive implementation. A tail call optimization would eliminate these function invocations.
  • We’ve traded the work of creating stack frames with creating function bindings. Both operations consume time and memory. Tail call optimization doesn’t create function references due to its modifying the function implementation in place to transform the recursive implementation to a loop.

PS:  Thanks for this js-drip, I was not aware of this concept.


Michael Brockington

unread,
Jul 11, 2014, 7:14:29 AM7/11/14
to js-drip-d...@googlegroups.com
I have to say, while I can see how this avoids the call stack, surely it just offloads performance issues somewhere else?

My gut feeling is that for functions that do not exceed the stack limit, execution would be much slower. Am I wrong? Is the difference significant?

Regards,
Mike

Narendra Sisodiya

unread,
Jul 11, 2014, 11:05:40 AM7/11/14
to Michael Brockington, js-drip-d...@googlegroups.com
2014-07-11 16:44 GMT+05:30 Michael Brockington <mike.bro...@gmail.com>:
I have to say, while I can see how this avoids the call stack, surely it just offloads performance issues somewhere else?

My gut feeling is that for functions that do not exceed the stack limit, execution would be much slower. Am I wrong? Is the difference significant?

Are you saying, function that exceed the stack limit, execution will be faster?
Reply all
Reply to author
Forward
0 new messages