緩存函數是一種提高函數性能的技術,在函數被調用時,會將計算結果緩存起來,以便在后續的調用中直接返回緩存的結果,從而減少了重復計算的時間。
緩存函數的實現通常包括兩個步驟:
-
判斷緩存是否存在:在函數被調用時,首先判斷緩存對象中是否已經存在該參數對應的緩存結果,如果有則直接返回緩存結果,否則進入下一步。
-
計算并緩存結果:如果緩存不存在,則進行函數的計算,并將計算結果保存到緩存對象中,然后返回計算結果。
使用緩存函數可以大大提高程序的性能,特別是對于一些需要耗費大量時間計算的函數,例如遞歸計算、數學公式計算等。但需要注意的是,由于緩存函數的緩存對象會占用一定的內存空間,因此需要適度使用緩存函數,避免出現內存溢出等問題。
首先查看以下的代碼,當我每次點擊的時候,都會打印一次5以內的隨機數,那么每次都要進行一次請求。這時我們就可以將數據進行一個緩存,當我們再次打印相同的結果時,直接返回緩存中的結果。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>緩存函數在項目中的性能優化</title>
</head>
<body><h1>緩存函數在項目中的性能優化</h1><button id="fetchButton">獲取數據</button><div id="resultContainer"><script>function fetchDataFromServer(postId) {console.log('從服務器端獲取數據:', postId)}const fetchButton = document.getElementById("fetchButton")const resultContainer = document.getElementById("resultContainer")fetchButton.addEventListener("click",() => {const postId = Math.floor(Math.random() * 5) + 1//調用這個函數傳遞參數fetchDataFromServer(postId)})</script></div>
</body></html>
這時,我們定義一個緩存函數
function createCachedFunction(originalFunction){const cache = {};return function(arg){if(cache[arg]){console.log("從緩存中進行數據獲取",arg)return Promise.resolve(cache[arg])}} return originalFunction(arg).then(result => {cache[arg] = result;console.log('第一次進行數據獲取,并實現了緩存',arg);return result;})
}
?定義之后我們也要去使用這個函數
const cacheFetchData = createCachedFunction(fetchDataFromServer)
fetchButton.addEventListener("click",() => {const postId = Math.floor(Math.random() * 5) + 1// fetchDataFromServer(postId)cacheFetchData(postId).then(data => {resultContainer.innerHTML = `<pre>${JSON.stringify(data,null,2)}</pre>`})
})
?
全部代碼為下列?
<h1>緩存函數在項目中的性能優化</h1><button id="fetchButton">獲取數據</button><div id="resultContainer"><script>// function fetchDataFromServer(postId) {console.log('從服務器端獲取數據:', postId)return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(response => response.json());}function createCachedFunction(originalFunction){const cache = {};return function(arg){if(cache[arg]){console.log("從緩存中進行數據獲取",arg)return Promise.resolve(cache[arg])}} return originalFunction(arg).then(result => {cache[arg] = result;console.log('第一次進行數據獲取,并實現了緩存',arg);return result;})}const cacheFetchData = createCachedFunction(fetchDataFromServer)const fetchButton = document.getElementById("fetchButton")const resultContainer = document.getElementById("resultContainer")fetchButton.addEventListener("click",() => {const postId = Math.floor(Math.random() * 5) + 1// fetchDataFromServer(postId)cacheFetchData(postId).then(data => {resultContainer.innerHTML = `<pre>${JSON.stringify(data,null,2)}</pre>`})})</script></div>