Split key and value, performance
Test the performance of different ways to split a string into key and value.
by some
CSS
body{font-family:monospace;}
JavaScript
var ROUNDS = 100; // How many rounds the thest should be run.
// Every test is in an array, first index is the name,
// the second is the testfunction that is called with a string.
// return an array with [key,value]
var tests = [
[
"indexOf",
function(a) {
var
p = a.indexOf('=');
key = a.slice(0, p), value = a.slice(p + 1);
return [key, value];
}
],
[
"split",
function(a) {
a.split('=');
var key = a[0],
value = a[1];
return [key, value];
}
],
[
"regexp: 2 separate ",
function(a) {
var key = /^(.+)=/.exec(a);
var value = /=(.*)$/.exec(a);
return [key, value];
}
],
[
"regexp: one",
function(a) {
return /([^=]*)=(.*)/.exec(a);
}
]
];
var data = (
function genData() {
function code(value) {
var result = [],
idx = 0;
do {
result.push(String.fromCharCode(idx % 26 + 65));
--value;
++idx;
} while (value > 0);
return result.join('');
}
var idx = 100,
data = [];
while (idx--) {
data.push(code(idx) + '=' + code(idx * 2))
}
return data;
})();
tests.forEach(function(test) {
var idx, f = test[1],
rounds = ROUNDS;
var start = +new Date;
while (rounds--) {
idx = data.length;
while (idx--) f(data[idx]);
}
var end = +new Date;
var div = document.createElement('div');
div.innerHTML = (end - start) + 'ms for "' + test[0] + '"';
document.body.appendChild(div);
});