indexOf or RegExp for finding chars

JavaScript performance comparison

Revision 4 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // 500-character random alphanumeric string.
    var haystack = 'gWkfGnHA0XyxkHQVVyDlBuPLzUfBqdWMrr3y470wbfmR4th66ZWI1SjNzsCpPLRlySGo5P6pAl0Wk3RYuJc2e0FA1r6RnVIPcTHdrb3I1sB97wSokAy0YQ4Oq4uvcdPOKVD1aeiWjxITyaOlPDw6KKFsJqUOlj7zo9gvIQaI1UvIL1dU1D3UAvB5fGzmGyWETwo6wZ1njFDSYmJEQWJThCAoqTs3lgvlb5LPOvCHkoJnhJp2i85a42VsVmcyBcjziiCHOPxwYr9OqVKLaIq1jimrBxBWfEQe8dR3R2NQaffP1PziBTCciuUB3DjpavVPEIYlwMHy7aYL5FkfbfoM6D14Ql3gj9TAkY3xWd2YCzxzIFZvKmf1DXTbEyyYMKnjvvPWHa4nMcUxeNMbOR5QANkWlaXdFHceySSbuXHzxMAISyDsVpW5dmQbY5LWHEwKtJNZbyIKn62X4tYlsYBbQOy2pbLMS8X1TYAyXItMyWvFIayR96oQ';
   
    var needleMap = {
      'a': true,
      'b': true,
      'c': true
    };
   
    var foundIndices = [];
};
</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
string.indexOf
for (var c in needleMap) {
  for (var i = 0; i < haystack.length; i++) {
    i = haystack.indexOf(c, i);
    if (i == -1) {
      break;
    }
    foundIndices.push(i);
  }
}

// Sort, so that we get consistent results with other tests.
foundIndices.sort(function(a, b) {
  return a - b;
});
pending…
map lookup
for (var i = 0; i < haystack.length; i++) {
  if (haystack.charAt(i) in needleMap) {
    foundIndices.push(i);
  }
}
pending…
RegExp.exec
needleArr = [];
for (k in needleMap) {
  needleArr.push(k);
}

var needleRegExp = new RegExp('[' + needleArr.join[''] + ']', 'g');
var match;
while (match = needleRegExp.exec(haystack)) {
  foundIndices.push(match.index);
}
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