Created
May 5, 2011 09:25
-
-
Save amasad/956782 to your computer and use it in GitHub Desktop.
Exploring freeing up the stack for tail-calls with setTimeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****************************************************************************** | |
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