contains() vs indexOf

JavaScript performance comparison

Revision 16 of this test case created by Connor

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  'use strict';
  
  if (!String.prototype.contains) {
    String.prototype.contains = function(searchString) {
      return this.indexOf(searchString) !== -1;
    };
  }
  
  function boyer_moore_horspool(haystack, needle) {
      var badMatchTable = {};
      var maxOffset = haystack.length - needle.length;
      var offset = 0;
      var last = needle.length - 1;
      var scan;
    
      // Generate the bad match table, which is the location of offsets
      // to jump forward when a comparison fails
      Array.prototype.forEach.call(needle, function (char, i) {
          badMatchTable[char] = last - i;
      });
   
      // Now look for the needle
      while (offset <= maxOffset) {
          // Search right-to-left, checking to see if the current offset at 
          // needle and haystack match.  If they do, rewind 1, repeat, and if we 
          // eventually match the first character, return the offset.
          for (scan=last; needle[scan] === haystack[scan+offset]; scan--) {
              if (scan === 0) {
                return offset;
              }
          }
   
          offset += badMatchTable[haystack[offset + last]] || last;
      }
   
      return -1;
  }
  
  var string = 'foobarfoobar';

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
indexOf
string.indexOf('rf') != -1;
pending…
contains
string.contains('rf');
pending…
~string.indexOf
~string.indexOf('rf');
pending…
!==
string.indexOf('rf') !== -1;
pending…
boyer_moore_horspool
boyer_moore_horspool(string, 'rf');
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.

0 Comments