純函數
函數式編程風格中有一個“純函數”的概念,純函數是一種無副作用的函數,除此之外純函數還有一個顯著的特點:對於同樣的輸入參數,總是返回同樣的結果。
性能提升
在平時的開發過程中,我們也應該儘量把無副作用的“純計算”提取出來實現成“純函數”,尤其是涉及到大量重複計算的過程,使用純函數+函數緩存的方式能夠大幅提高程序的執行效率。
Memoize
我們可以創建一個獨立的函數來記憶任何函數。我們將此函數稱爲memoize。在傳入相同的參數時直接返回上次緩存的結果,這樣在計算大量有重複數據時,可以提供性能,
function memoize(func) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args)
if(!cache.hasOwnProperty(key)) {
cache[key] = func.apply(this, args)
}
return cache[key]
}
}
function sum(n1, n2) {
const sum = n1 + n2
console.log(`${n1}+${n2}=${sum}`)
return sum
}
const memoizedSum = memoize(sum)
memoizedSum(1, 2) // 會打印出:1+2=3
memoizedSum(1, 2) // 沒有輸出
memoizedSum在第一次執行時將執行結果緩存在了閉包中的緩存對象cache中,因此第二次執行時,由於輸入參數相同,直接返回了緩存的結果。
更好的選擇是使用ES6+支持的Map對象
const memoize2 = fn => {
const cache = new Map();
const cached = function(...val) {
return cache.has(val) ? cache.get(val) : cache.set(val, fn.apply(this, val)) && cache.get(val);
};
cached.cache = cache;
return cached;
};