contains() vs indexOf (v16)

Revision 16 of this benchmark created by Connor on


Setup

'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';

Test runner

Ready to run.

Testing in
TestOps/sec
indexOf
string.indexOf('rf') != -1;
ready
contains
string.contains('rf');
ready
~string.indexOf
~string.indexOf('rf');
ready
!==
string.indexOf('rf') !== -1;
ready
boyer_moore_horspool
boyer_moore_horspool(string, 'rf');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.