Safari 尾调用优化和蹦床Trampoline技术性能对比(使用 Safari 打开) (v4)

Revision 4 of this benchmark created on


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 = 5000000;

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
使用Trampoline 转换后的尾调用

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.