JS簡單實現瀏覽器緩存淘汰策略

當我們打開一個網頁的時候,它回去查詢瀏覽器緩存,看是否有要請求的文件,如果儲存,就會返回緩存的文件。如果不存在,才會請求服務器。
這就是 瀏覽器緩存

瀏覽器緩存是一種在本地保存資源的副本,他的大小是有限制的。當我們請求過多的時候,繼續請求就需要緩存去確定哪些數據應該被保留,哪些數據應該被刪除。
這就是 瀏覽器緩存淘汰策略
常見的瀏覽器淘汰策略有以下幾種

  • 先進先出(FIFO)
  • 最少使用(LFU)
  • 最近最少使用(LRU)

JS實現FIFO

 class FIFOCache {
        constructor(limit) {
          this.limit = limit || [];
          this.map = {};
          this.keys = [];
        }
        set(key, value) {
          let map = this.map;
          let keys = this.keys;
          if (!Object.prototype.hasOwnProperty.call(map, key)) {
            if (keys.length === this.limit) {
              delete map[keys.shift()];
            }
            keys.push(key);
          }
          map[key] = value;
        }
        get(key) {
          return this.map[key];
        }
      }

JS實現LRU

vue的keep-alive就是使用的LRU

 class LRUCache {
        constructor(limit) {
          this.cache = new Map();
          this.limit = limit;
        }
        put(key, value) {
          if (this.cache.has(key)) {
            this.cache.delete(key);
          } else if (this.cache.size >= this.limit) {
            this.cache.delete(this.cache.keys().next().value);
          }
          this.cache.set(key, value);
        }
        get(key) {
          if (this.cache.has(key)) {
            let temp = this.cache.get(key);
            this.cache.delete(key);
            this.cache.set(key, temp);
            return temp;
          }
          return -1;
        }
      }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。