Chrome 使用尾调用和trampoline的性能对比(无尾调用优化) (v2)

Revision 2 of this benchmark created on


Description

因为 Chrome 没有尾调用优化,为了防止调用栈溢出,这里设置更小的迭代深度来完成测试。

Setup

/**
* Trampoline 函数,将尾递归函数转换成循环
*/
function trampoline(fn) {
    return function(...args) {
        let result = fn(...args);
        while (typeof result === 'function') {
            result = result();
        }
        return result;
    };
}
// 输入
const input = 0
const maxNum = 7863;

Test runner

Ready to run.

Testing in
TestOps/sec
标准尾递归
function test(n, max) {
    'use strict';
    if (n === max) {
        return n;
    }
    return test(n + 1, max);
}
test(input, maxNum);
ready
使用蹦床技术尾递归
function test(n, max) {
    'use strict';
    if (n === max) {
        return n;
    }
    return () => test(n + 1, max);
}

const trampolinedtest = trampoline(test);
trampolinedtest(input, maxNum);
ready
循环方式
function test(start, end) {
    let sum = start
    ;
    for (let i = start; i < end; i++) {
        sum++;
    }
    return sum;
}
test(input, maxNum)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.