Home > Web Front-end > JS Tutorial > body text

The difference between the three data storage methods of JavaScript

PHPz
Release: 2018-09-28 13:13:46
Original
2312 people have browsed it

This chapter introducesthe differences between the three data storage methods of javaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The common points between sessionStorage, localStorage and cookies:

are all saved on the browser side and have the same origin .

The difference between sessionStorage, localStorage and cookies:

Cookie data is always carried in the http request from the same origin (even if it is not needed), that is, the cookie is stored in the browser Transferred back and forth to the server. SessionStorage and localStorage do not automatically send data to the server, but only save it locally. Cookie data also has the concept of path, which can restrict cookies to only belong to a certain path.

The storage size limit is also different. Cookie data cannot exceed 4k. At the same time, because each http request carries cookies, cookies are only suitable for saving very small data, such as session identifiers. Although sessionStorage and localStorage also have storage size limits, they are much larger than cookies and can reach 5M or more.

The data validity period is different. sessionStorage: it is only valid until the current browser window is closed, and naturally it cannot be persisted; localStorage: it is always valid and is saved even when the window or browser is closed, so it is used as persistent data; Cookies are only valid until the set cookie expiration time, even if the window or browser is closed.

Different scopes, sessionStorage is not shared in different browser windows, even on the same page; localStorage is shared in all same-origin windows; cookies are also shared in all same-origin windows .

Web Storage supports event notification mechanism, which can send data update notifications to listeners.

Web Storage’s api interface is more convenient to use.

The encapsulated localStorage method can control the number of stored data and the time

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

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

  $.extend(Cache, {
    config: {
      size: 5,
      // lifeTime: 86400 //一天的秒数
      lifeTime: 1*60
    },
    localStorage: window.localStorage,
    memQueue: (function () {
      if (support()) {
        var jsonStr = window.localStorage.getItem('LRUConfig');
        return jsonStr ? JSON.parse(jsonStr) : {
          keys: {},
          objs: []
        };
      } else {
        return {};
      }
    })(),

    get: function(appid, url) {
      if (true == support()) {
        var key = appid + ':' + url;
        //开始做LRU算法。
        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;
          }
        }
        //如果isFresh为假,就是已过期,则返回null,否则从localStorage中取
        return (false == isFresh) ? null : this.localStorage[key];
      }
    },
    set: function(appid, url, value) {
      if (true == support()) {
        var key = appid + &#39;:&#39; + url;
        var lruKey = this.getLRU();
        //淘汰最近最少使用的这个。
        //另外起一个方法读取最符合淘汰的这个
        //前提是当前这个key,不在localStorage里面。
        if (lruKey) {
          this.localStorage.removeItem(lruKey);
        }
        //开始设置一下这个值
        //为了兼容性,用以下方法设置
        if (typeof this.memQueue.objs != &#39;undefined&#39; &&
          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;
        //当前的key,也必须lru一下
        this.LRU(key);
        //lru结束

        this.localStorage.setItem(&#39;LRUConfig&#39;, JSON.stringify(this.memQueue));
      }
    },
    /*
     * 近期最少使用算法
     */
    LRU: function(key) {
      var memQueue = this.memQueue;
      if (typeof memQueue.objs != &#39;undefined&#39;) {
        var _o = memQueue.objs;

        //开始计算那个要淘汰的key,
        //就是那个times最大的,如果times最大的有几个
        //则返回那个time最小的
        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 = {
            &#39;key&#39;: key,
            &#39;times&#39;: 0,
            &#39;time&#39;: (new Date()).getTime(),
            &#39;life&#39;: (new Date()).getTime()
          };
          this.memQueue.keys[key] = _to;
          this.memQueue.objs.push(_to);
        }
        _o.sort(function(f, s) {
          //按times降序排列。
          if (f.times < s.times) {
            return 1;
          } else if (f.times > s.times) {
            return -1;
          } else {
            //开始比较time
            //按time,时间升序排列
            if (f.time < s.time) {
              return -1;
            } else {
              return 1;
            }
          }
        });
      } else {
        this.memQueue.objs = [];
        this.memQueue.keys = {};
        var _to = {
          &#39;key&#39;: key,
          &#39;times&#39;: 0,
          &#39;time&#39;: (new Date()).getTime(),
          &#39;life&#39;: (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 {
    &#39;cache&#39;: Cache
  };
});
Copy after login

Usage method

var cache = require(&#39;cache&#39;);
// set 值
cache.Cache.set(&#39;ip&#39;, &#39;你自己的一个url&#39;, value);

// get值
cache.Cache.get(&#39;ip&#39;)
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!