DIV CSS 佈局教程網

sessionStorage、localStorage 與 cookie 三大前端存儲方案對比
編輯:JavaScript基礎知識     

瀏覽器端有三種常見的資料存放位置:sessionStorage、localStorage 與 cookie。它們看似功能重疊,實際在傳輸行為、容量、生命週期與作用域上差異明顯,選錯往往會導致效能問題或資料錯亂。

共同點

三者都保存在瀏覽器端,且都受同源策略約束。

關鍵差異

傳輸行為:cookie 會在同源的 HTTP 請求中自動攜帶(無論是否需要),也就是在瀏覽器與伺服器之間反覆往返;sessionStorage 與 localStorage 不會主動上送,僅在本地保存。cookie 還有 path 概念,可以限定其作用於某個路徑之下。

容量上限:cookie 不能超過 4KB,加上每次請求都要攜帶,因此只適合存放極少量的資料,例如工作階段識別碼。Web Storage 的上限雖同樣存在,但通常可達 5MB 甚至更高。

資料有效期:

  • sessionStorage:僅在當前瀏覽器窗口關閉前有效,無法持久化。
  • localStorage:始終有效,窗口或瀏覽器關閉後仍會保留,適合作為持久資料。
  • cookie:在設定的過期時間之前一直有效,即使窗口或瀏覽器關閉。

作用域:sessionStorage 不在不同瀏覽器窗口之間共享(即使是同一個頁面);localStorage 與 cookie 則在所有同源窗口中共享。

其他優勢:Web Storage 支援事件通知機制,可以把資料更新推送給監聽者;其 API 設計也比手動拼 cookie 字串更方便。

為 localStorage 加上容量與時間控制

原生 localStorage 只提供「存」與「取」,既不管數量也不管過期。實務上往往需要一層封裝,結合 LRU(近期最少使用)淘汰策略與 TTL(存活時間)機制:

define(function (require) {
  var $ = require('jquery');
  var Cache = {};

  function support() {
    return !(typeof window.localStorage === 'undefined');
  }

  $.extend(Cache, {
    config: {
      size: 5,          // 最多保存的條數
      lifeTime: 1 * 60  // 存活秒數
    },
    localStorage: window.localStorage,
    memQueue: (function () {
      if (support()) {
        var jsonStr = window.localStorage.getItem('LRUConfig');
        return jsonStr ? JSON.parse(jsonStr) : { keys: {}, objs: [] };
      }
      return {};
    })(),

    get: function (appid, url) {
      if (true == support()) {
        var key = appid + ':' + url;
        this.LRU(key);   // 更新 LRU 計次

        var isFresh = true;
        var nowTime = (new Date()).getTime() / 1000;

        if (key in this.memQueue.keys) {
          var cacheTime = this.memQueue.keys[key].life / 1000;
          // 超過配置的 lifeTime 則清除該快取
          if (nowTime - cacheTime >= this.config.lifeTime) {
            delete this.memQueue.keys[key];
            for (var i = 0, len = this.memQueue.objs.length; i < len; i++) {
              var _o = this.memQueue.objs[i];
              if (_o.key == key) {
                this.memQueue.objs.splice(i, 1);
                break;
              }
            }
            isFresh = false;
          }
        }
        return (false == isFresh) ? null : this.localStorage[key];
      }
    },

    set: function (appid, url, value) {
      if (true == support()) {
        var key = appid + ':' + url;
        var lruKey = this.getLRU();
        // 淘汰最近最少使用的一項
        if (lruKey) {
          this.localStorage.removeItem(lruKey);
        }

        // 為相容性先移除同名鍵
        if (typeof this.memQueue.objs != 'undefined' && this.memQueue.objs.length <= this.config.size) {
          this.localStorage.removeItem(key);
        } else {
          while (this.memQueue.objs.length >= this.config.size) {
            var lruKey = this.getLRU();
            if (lruKey) {
              this.localStorage.removeItem(lruKey);
              delete this.memQueue.keys[lruKey];
              for (var i = 0; i < this.memQueue.objs.length; i++) {
                var _o = this.memQueue.objs[i];
                if (_o.key == lruKey) {
                  this.memQueue.objs.splice(i, 1);
                  break;
                }
              }
            }
          }
        }

        this.localStorage[key] = value;
        this.LRU(key);
        this.localStorage.setItem('LRUConfig', JSON.stringify(this.memQueue));
      }
    },

    /* 近期最少使用演算法 */
    LRU: function (key) {
      var memQueue = this.memQueue;
      if (typeof memQueue.objs != 'undefined') {
        var _o = memQueue.objs;
        var isIn = false;
        for (var i = 0, len = _o.length; i < len; i++) {
          _o[i].times = (key == _o[i].key) ? 0 : _o[i].times + 1;
          _o[i].time = (key == _o[i].key) ? (new Date()).getTime() : _o[i].time;
          if (key == _o[i].key && false == isIn) {
            isIn = true;
          }
        }
        if (false == isIn) {
          var _to = {
            'key': key,
            'times': 0,
            'time': (new Date()).getTime(),
            'life': (new Date()).getTime()
          };
          this.memQueue.keys[key] = _to;
          this.memQueue.objs.push(_to);
        }
        _o.sort(function (f, s) {
          // 按 times 降序;times 相同時按 time 升序
          if (f.times < s.times) {
            return 1;
          } else if (f.times > s.times) {
            return -1;
          } else {
            if (f.time < s.time) {
              return -1;
            } else {
              return 1;
            }
          }
        });
      } else {
        this.memQueue.objs = [];
        this.memQueue.keys = {};
        var _to = {
          'key': key,
          'times': 0,
          'time': (new Date()).getTime(),
          'life': (new Date()).getTime()
        };
        this.memQueue.keys[key] = _to;
        this.memQueue.objs.push(_to);
        return null;
      }
    },

    /* 讀取需要淘汰的一項 */
    getLRU: function () {
      var _o = this.memQueue.objs;
      if (_o) {
        return (_o.length >= this.config.size) ? _o.shift().key : null;
      }
      return null;
    }
  });

  return { 'cache': Cache };
});

使用方式:

var cache = require('cache');

// 寫入
cache.Cache.set('ip', '你自己的一個url', value);

// 讀取
cache.Cache.get('ip');

實作要點是把「計次」與「時間戳」一併記在 LRUConfig 這個輔助鍵上:讀取時更新計次、檢查是否過期,寫入時若超出上限就淘汰計次最高(最久未被使用)的那一項。這樣便在原生 API 之上補出了容量控制與 TTL 能力。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved