Parse cookies

JavaScript performance comparison

Revision 2 of this test case created by 1Pupik1989

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  encode = encodeURIComponent;
  
  decode = decodeURIComponent;
  
  function parse(str) {
    var obj = {};
    var pairs = str.split(/ *; */);
    var pair;
    if ('' == pairs[0]) return obj;
    for (var i = 0; i < pairs.length; ++i) {
      pair = pairs[i].split('=');
      obj[decode(pair[0])] = decode(pair[1]);
    }
    return obj;
  }
  
  getAllCookies = function(str) {
    var colIx, egalIx, obj, pair, prevIx;
    obj = {};
    prevIx = 0;
    //str = decode(str);
    while (true) {
      colIx = str.indexOf(';', prevIx);
      pair = colIx === -1 ? str.substring(prevIx).trim() : str.substring(prevIx, colIx - 1).trim();
      if (pair === '') {
        return obj;
      }
      egalIx = pair.indexOf('=');
      obj[pair.substring(0, egalIx - 1)] = pair.substring(egalIx + 1);
      if (colIx === -1) {
        return obj;
      }
      prevIx = colIx + 1;
    }
  };
  
  function parseAllCookies(string){
    var reg = /(\S+)\=(\S+)[^;]/g;
    var match = null;
    var matches = {};
    while (match = reg.exec(string)) {
      matches[ match[1] ] = match[2];
    }
    return matches;
  };
  
  function parseAllCookies2(cookie){
    var pairs = cookie.split(";");
    var length = pairs.length;
    var cookies = {};  
    for (var i=0; i<length; i++){
      var pair = pairs[i].split("=");
      cookies[pair[0]] = unescape(pair[1]);
    }
    return cookies;
  };
  
  function parseAllCookies3(cookie){
    var aKeys = "{"+cookie.replace(/([^;\s=]+)=([^;]+)/g,"\"$1\":\"$2\"").replace(/;/g,",")+"}";
    return JSON.parse(aKeys);
  };
  
  var testCoo = '__qca=P0-1279630214-1361530382272; gauthed=1; sgt=id=c0de28d9-13bc-4c2d-bd31-377f58a5ef52';

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
express parse
parse(testCoo);
pending…
getAllCookies
getAllCookies(testCoo);
pending…
parseAllCookies
parseAllCookies(testCoo);
pending…
parseAllCookies 2
parseAllCookies2(testCoo);
pending…
parseAllCookies 3
parseAllCookies3(testCoo);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments