Summarize the differences between JavaScript three types of data storage _ basics

Source: Internet
Author: User
Tags sessionstorage

The common denominator between sessionstorage, localstorage, and cookies:
are stored in the browser-side and are homologous.

The difference between sessionstorage, localstorage, and cookies:
cookie data is always carried in a homologous HTTP request, even if it is not needed, that is, the cookie is passed back and forth between the browser and the server. Sessionstorage and Localstorage do not automatically send the data to the server, which is saved locally. Cookie data also has the concept of path, which restricts cookies to only one path.
Storage size limits vary, cookie data cannot exceed 4k, and because each HTTP request carries a cookie, cookies are only suitable for storing very small data, such as session identities. Sessionstorage and Localstorage, though also limited in size, are much larger than cookies and can reach 5M or greater.
Data expiration is different, Sessionstorage: only valid before the current browser window closes, naturally it is impossible to persist; Localstorage: always valid, window or browser shutdown is persisted, and therefore used as persistent data ; The cookie is valid only until the cookie expiration time is set, even if the window or browser is closed.
Scopes are different, sessionstorage are not shared in different browser windows, even the same page, Localstorage are shared in all cognate windows, and cookies are shared in all cognate windows.
The Web Storage supports the event notification mechanism, which sends notifications of data updates to listeners.
Web Storage API interface is more convenient to use.

Encapsulated Localstorage method that controls the number of bars in which data is stored, 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/day Seconds lifetime:1*60}, Loca LStorage:window.localStorage, Memqueue: (function () {if (support ()) {var jsonstr = Window.localstora
        Ge.getitem (' Lruconfig '); Return JSONSTR?
      Json.parse (JSONSTR): {keys: {}, OBJS: []};
      else {return {};
        }) (), get:function (AppID, URL) {if (true = = Support ()) {var key = AppID + ': ' + URL;
        Start to do the LRU algorithm. This.
        LRU (key);
        The LRU algorithm ends.
        var Isfresh = true;
        var nowtime = (new Date ()). GetTime ()/1000;
          if (key in This.memQueue.keys) {var cacheTime = this.memqueue.keys[key].life/1000;
  If the expiration time exceeds the configured lifetime,//the current cache is cleared        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; }//If Isfresh is false, or is expired, returns NULL, otherwise the return from localstorage (false = = Isfresh)?
      Null:this.localstorage[key];
        }, Set:function (AppID, URL, value) {if (true = = Support ()) {var key = AppID + ': ' + URL;
        var lrukey = This.getlru ();
        Eliminate the least recently used one.
        Another method to read the most suitable for the elimination of this//premise is the current key, not localstorage inside.
        if (Lrukey) {This.localStorage.removeItem (Lrukey); //Start Setting this value//For compatibility, use the following method to set the IF (typeof this.memQueue.objs!= ' undefined ' && th Is.memqueue.objs.lEngth <= this.config.size) {This.localStorage.removeItem (key);
            else {while (this.memQueue.objs.length >= this.config.size) {var lrukey = This.getlru ();
            Eliminate the least recently used one.
              Another method reads the most conforming to the elimination of this 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; The current key must also LRU this.
        LRU (key);
      LRU End This.localStorage.setItem (' Lruconfig ', Json.stringify (This.memqueue));
      }, * * The least Recently used algorithm/lru:function (key) {var memqueue = This.memqueue; if (typeoF memqueue.objs!= ' undefined ') {var _o = Memqueue.objs;
        Start to calculate the key to be eliminated,//is the largest of the times, if the times the largest number of//Then return that time the smallest 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 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) {//in descending order of times.
          if (F.times < s.times) {return 1;
          else if (F.times > S.times) {return-1;
     } else {       Start comparing time//by times, in ascending order of 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 D
        Ate ()). GetTime ()};
        This.memqueue.keys[key] = _to;
        This.memQueue.objs.push (_to);
      return null;
      }, * * read one of the items that needs to be eliminated/getlru:function () {var _o = This.memQueue.objs;
      if (_o) {return (_o.length >= this.config.size) _o.shift (). Key:null;

    return null;


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

 });

How to use

var cache = require (' cache ');
Set value
cache. Cache.set (' IP ', ' One of your own URLs ', value);

Get value
cache. Cache.get (' IP ')

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.