简体   繁体   English

我怎样才能减少这段代码的执行时间

[英]How can i reduce the time of execution of this code

var yourself = {
    fibonacci : function(n) {
        return n === 0 ? 0 : n === 1 ? 1 : 
        this.fibonacci(n -1) + this.fibonacci (n-2)
    }
};

This function is constantly setting the value of its 'fibonacci' property based on the arguement supplied for 'n' parameter of the function.该函数根据为函数的 'n' 参数提供的参数不断设置其 'fibonacci' 属性的值。 I would like to refactor the function to reduce execution time我想重构函数以减少执行时间

Using dynamic programming, Memoization that cache the already calculated result使用动态规划,缓存已经计算的结果

read more about memoization here在此处阅读有关记忆的更多信息

const memoFib = function () {
    let memo = {}
    return function fib(n) {
        if (n in memo) { return memo[n] }
        else {
            if (n <= 1) { memo[n] = n }
            else { memo[n] = fib(n - 1) + fib(n - 2) }
            return memo[n]
        }
    }
}

const fib = memoFib()
console.log(fib(50));

You could implement some kind of caching.你可以实现某种缓存。 This way you don't need to recalculate the same result multiple times.这样您就不需要多次重新计算相同的结果。

 var yourself = { fibonacci : function(n, cache = new Map()) { if(cache.has(n)) return cache.get(n); if(n === 0) return 0; if(n === 1) return 1; const start = this.fibonacci(n-1, cache); const end = this.fibonacci(n-2, cache); cache.set(n-1, start); cache.set(n-2, end); return start + end; } }; console.log(yourself.fibonacci(40));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM