CPS in JavaScript

sum1

Enter N to calculate 0+1+2+...+N recursively in JavaScript using ordinary recursion, i.e.,

function sum1(n) {
    if (n == 0)
        return 0;
    else
        return n+sum1(n-1);
}

Large N triggers a stack overflow exception. (You can experiment, but in one session, I found stack overflows at the following points: Firefox 20, N > 32365; Safari 6.0.4, N > 37445; Google Chrome 26, N > 13821.)

sum2

Enter N to calculate 0+1+2+...+N recursively in JavaScript using Continuation-Passing Style with Trampolines.

Note: Large N can crash some browsers because this code generates very deeply nested heap objects (instead of a deep stack). For old versions of Safari, N > 100000 would crash the browser; today, Safari seems to be immune to that problem but requires approximately N*500 bytes to run, which means N=20000000 requires 10 GB of RAM. Firefox crashes when N=30000000.

results