要優化JavaScript遞歸函數的性能,您可以采取以下策略:
function factorial(n, accumulator = 1) {
if (n === 0) return accumulator;
return factorial(n - 1, n * accumulator);
}
function fibonacci(n, memo = {}) {
if (n <= 1) return n;
if (!memo[n]) memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
function factorial(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result.concat(left, right);
}
function fibonacci(n) {
const dp = [0, 1];
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
請注意,優化遞歸函數的性能可能需要根據具體問題進行調整。在進行優化時,請務必測試代碼以確保其正確性和性能改進。