Cookie Parsing

JavaScript performance comparison

Revision 8 of this test case created

Info

Comparing two RegExp and String parsing methods for getting a value from a cookie.

Then adding in Lawnchair's cookie parser, for fun.

Preparation code

<script>
  function generateCookieString(count) {
    var name = "name",
        stringParts = [],
        array = new Array(6);
    for(var j = 1; j <= count; j++)
    {
        stringParts.push(name + j + '=' + array.join(name+j));
    }
    return stringParts.join(';');
  }
 
  function string(name, cookie) {
    setPos = cookie.indexOf(name + '='), stopPos = cookie.indexOf(';', setPos);

    // Dataset does not exist, attempt to register default
    return !~setPos ? null : cookie.substring(
    setPos, ~stopPos ? stopPos : undefined).split('=')[1];
  }

  function regexp(name, cookie) {
    var regex = new RegExp(name + '=([^;]*)', 'g'),
        result = regex.exec(cookie);

    return result[1] || null;
  }

  function lawnchair(name, cookie) {
    var nameEQ = name + '=',
        ca = cookie.split(';'),
        len = ca.length,
        i = 0,
        c;

    for (; i < len; i++) {
      c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1, c.length);
      }
      if (c.indexOf(nameEQ) == 0) {
        return c.substring(nameEQ.length, c.length);
      }
    }
    return null;

  }

  function simplesplits(name, cookie) {

    var parts = cookie.split(name);

    return parts.length === 0 ? null : parts[1].split('=')[1].split(';')[0];

  }

  var cookieString = generateCookieString(30);
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
String
string('name15', cookieString);
pending…
RegExp
regexp('name15', cookieString);
pending…
Lawnchair
lawnchair('name15', cookieString);
pending…
Simple splits
simplesplits('name15', cookieString);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment