Parse cookies
JavaScript performance comparison
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);
};
function parseAllCookies4(cookie){
var matches = {};
cookie.replace(/([^=\s]+)=([^;]+)/g,function(a,b,c){
matches[b] = c;
});
return matches;
};
function parseAllCookies5(cookie) {
var pairs = cookie.split(/[;=]/);
var length = pairs.length, matches = {};
var value;
for(var i=0;i<length;i+=2){
value = pairs[i+1];
if(typeof value !== "undefined"){
matches[ pairs[i] ] = value;
}
}
return matches;
};
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.
| Test | Ops/sec | |
|---|---|---|
express parse |
|
pending… |
getAllCookies |
|
pending… |
parseAllCookies |
|
pending… |
parseAllCookies 2 |
|
pending… |
parseAllCookies 3 |
|
pending… |
parseAllCookies 4 |
|
pending… |
parseAllCookies 5 |
|
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:
- Revision 1: published by Simon
- Revision 2: published by 1Pupik1989
- Revision 3: published by 1Pupik1989
- Revision 4: published by Simon
0 comments