設計模式-備忘錄模式

備忘錄模式主要用於優化比較耗時的計算,經過將計算結果緩存到內存中,這樣對於一樣的輸入值,下次只須要中內存中讀取結果。git

const memento = func => {
  const cache = {}
  return function() {
    let key = arguments[0]
    return cache[key] || (cache[key] = func.apply(null, arguments))
  }
}
複製代碼

使用場景:github

  • 緩存搜索結果,避免重複請求的網絡開銷
  • 緩存計算結果,避免屢次計算的內存開銷

博客地址 gitbook小冊緩存

相關文章
相關標籤/搜索