Performance comparison of String extract vs RegExp
by Arnaud Buchholz
JavaScript
function log (text) {
var line = document.createElement("div");
line.appendChild(document.createTextNode(text));
document.body.appendChild(line);
}
function test (label, cb) {
var dtStart = new Date(),
count = 0;
while (new Date() - dtStart < 1000) {
cb();
++count;
}
log(label + ": " + count.toLocaleString('en-US'));
return count;
}
var valueToProcess = "a.bc.d.efg.h";
function checkValue(value, expected) {
if (value !== expected) {
log("Fail !");
throw new Error("Fail !");
}
}
function checkFirst(value) {
checkValue(value, "bc");
}
function checkSecond(value) {
checkValue(value, "h");
}
var a = test("Using indexOf and substr method", function () {
var firstDot = valueToProcess.indexOf("."),
secondDot = valueToProcess.indexOf(".", firstDot + 1),
lastDot = valueToProcess.lastIndexOf(".");;
checkFirst(valueToProcess.substr(firstDot + 1, secondDot - firstDot - 1));
checkSecond(valueToProcess.substr(lastDot + 1));
});
var b = test("Using regular expression", function () {
var result = /^[^\.]+\.([^\.]+)(?:\.[^\.]+)+\.([^\.]+)$/.exec(valueToProcess);
checkFirst(result[1]);
checkSecond(result[2]);
});
log("Gain/Loss: " + Math.floor(1000 * (b - a) / a)/10 + "%");