Skip to content

Instantly share code, notes, and snippets.

@amasad
Created May 5, 2011 09:25
Show Gist options
  • Save amasad/956782 to your computer and use it in GitHub Desktop.
Save amasad/956782 to your computer and use it in GitHub Desktop.
Exploring freeing up the stack for tail-calls with setTimeout
/******************************************************************************
Without tail-call
******************************************************************************/
var times = 0;
function test(n) {
if (++n >= 10000) {
if (++times == 100) console.timeEnd('no-tail')
} else {
test(n);
}
}
console.time('no-tail');
for (var i = 0; i < 100; i++) {
test(0);
}
/******************************************************************************
With tail-call
******************************************************************************/
var LIMIT = 100;
(function() {
var stackSize = 0;
tail = function(fn, args) {
if (++stackSize > LIMIT) {
stackSize = 0;
setTimeout(function() { fn.apply(null, args); }, 0);
} else {
fn.apply(null, args);
}
};
})();
var times = 0;
function test(n) {
if (++n >= 10000) {
if (++times == 100) console.timeEnd('tail-call');
} else {
tail(test, [n]);
}
}
console.time('tail-call');
var taken = 0;
for (var i = 0; i < 100; i++) {
test(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment