Testing two strings using logical or vs regexp

JavaScript performance comparison

Test case created by Dan Nye

Info

When testing an event object's type property, I want to know if it is quicker to test for one of two values using string comparisons and a logical OR, or whether it is quicker to use any one of a number of regular expressions

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var possibility1 = 'touchend';
    var possibility2 = 'touchcancel';
   
};
</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
Logical OR
var theString1 = possibility1;
var tempVar1 = 0;
if (theString1 == 'touchend' || theString1 == 'touchcancel') {
   tempVar1++;   // Do something to ensure comparison will be run
}

var theString2 = possibility2;
var tempVar2 = 0;
if (theString2 == 'touchend' || theString2 == 'touchcancel') {
   tempVar2++;   // Do something to ensure comparison will be run
}
 
pending…
Regexp 1
var theString1 = possibility1;
var tempVar1 = 0;
if (theString1.match(/(touchend|touchcancel)/)) {
   tempVar1++;   // Do something to ensure comparison will be run
}

var theString2 = possibility2;
var tempVar2 = 0;
if (theString2.match(/(touchend|touchcancel)/)) {
   tempVar2++;   // Do something to ensure comparison will be run
}
 
pending…
Regexp 2
var theString1 = possibility1;
var tempVar1 = 0;
if (theString1.match(/(end|cancel)$/)) {
   tempVar1++;   // Do something to ensure comparison will be run
}

var theString2 = possibility2;
var tempVar2 = 0;
if (theString2.match(/(end|cancel)$/)) {
   tempVar2++;   // Do something to ensure comparison will be run
}
 
pending…
Regexp 3
var theString1 = possibility1;
var tempVar1 = 0;
if (theString1.match(/(d|l)$/)) {
   tempVar1++;   // Do something to ensure comparison will be run
}

var theString2 = possibility2;
var tempVar2 = 0;
if (theString2.match(/(d|l)$/)) {
   tempVar2++;   // Do something to ensure comparison will be run
}
 
pending…
Regexp 4
var theString1 = possibility1;
var tempVar1 = 0;
if (theString1.match(/(d$|l$)/)) {
   tempVar1++;   // Do something to ensure comparison will be run
}

var theString2 = possibility2;
var tempVar2 = 0;
if (theString2.match(/(d$|l$)/)) {
   tempVar2++;   // Do something to ensure comparison will be run
}
 
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