Condition VS RegExp VS indexOf

JavaScript performance comparison

Revision 4 of this test case created

Preparation code

<script>
  Benchmark.prototype.setup = function() {
    var a = (Math.random() * 15) | 0,
        b = (Math.random() * 15) | 0;
var gTab = [1, 2, 3, 4, 5];
var gRg = /^1|2|3|4|5$/;
  };
</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
Simple condition
if (a == 1 || a == 2 || a == 3 || a == 4 || a == 5) {
  'ok';
}
if (b == 1 || b == 2 || b == 3 || b == 4 || b == 5) {
  'ok';
}
pending…
indexOf
if ([1, 2, 3, 4, 5].indexOf(a) !== -1) {
  'ok';
}
if ([1, 2, 3, 4, 5].indexOf(b) !== -1) {
  'ok';
}
pending…
indexOf (not litteral)
var tab = [1, 2, 3, 4, 5];
if (tab.indexOf(a) !== -1) {
  'ok';
}
if (tab.indexOf(b) !== -1) {
  'ok';
}
pending…
RegExp
if (/^1|2|3|4|5$/.test(a)) {
  'ok';
}
if (/^1|2|3|4|5$/.test(b)) {
  'ok';
}
pending…
RegExp (not litteral)
var rg = /^1|2|3|4|5$/;
if (rg.test(a)) {
  'ok';
}
if (rg.test(b)) {
  'ok';
}
pending…
RegExp (global)
if (gRg.test(a)) {
  'ok';
}
if (gRg.test(b)) {
  'ok';
}
pending…
indexOf (global)
if (gTab.indexOf(a) !== -1) {
  'ok';
}
if (gTab.indexOf(b) !== -1) {
  'ok';
}
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