Cookie Parsing (v5)

Revision 5 of this benchmark created on


Description

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

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

Preparation HTML

<script>
  var set = 'Cookie',
      cookie = 'cookie1=cookie%20val%201; theCookie=value2; anotherCookie=value3; Cookie=value4; finally=;last=123'
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
String
var setPos = cookie.indexOf(set + '='),
    stopPos = cookie.indexOf(';', setPos);
return !~setPos ? null : cookie.substring(
setPos, ~stopPos ? stopPos : undefined).split('=')[1];
ready
RegExp (exec)
var regex = new RegExp(set + '=([^;]*)', 'g');
return regex.exec(cookie)[1] || null;
ready
Lawnchair
var name = set;
var nameEQ = name + "=";
var ca = cookie.split(';');
var len = ca.length;
for (var i = 0; i < len; i++) {
 var 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;
ready
RegExp (match)
var val = cookie.match(set + '=([^;]*)') || null;
return val.length ? val[1] : val;
ready
Another Method
var cookies = {};
for (var a = cookie.split("; "), b = 0; b < a.length; b++) cookies[a[b].slice(0, a[b].indexOf("="))] = a[b].slice(a[b].indexOf("=") + 1);
return cookies[set];
ready
Another Method 2
for (var a = cookie.split("; "), b = 0; b < a.length; b++) {
 var idx = a[b].indexOf("="),
     theName = a[b].slice(0, idx);
 if (theName == set) return a[b].slice(idx + 1)
}
return null;
ready

Revisions

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