startsWith speed comparison (v20)

Revision 20 of this benchmark created on


Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.0.0/underscore.string.js"></script>

Setup

a = ["test"];
    for (var i = 0; i < 10000; i++) {
      a.push("some other stuff");
    }
    str = a.join();
    
    String.prototype.startsWith = function(needle) {
        return this.slice(0, needle.length) === needle;
    };
    
    String.prototype.startsWithLoop = function(needle) {
      var that = this;
        var ceil = needle.length;
        for(var i = 0; i < ceil; i++) {
                if(that[i] !== needle[i]) return false;
        }
        return true;
    }
    
    function startsWith(haystack, needle) {
        return haystack.slice(0, needle.length) === needle;
    }
    
    function startsWithLoop(haystack, needle) {
        var ceil = needle.length;
        for(var i = 0; i < ceil; i++) {
                if(haystack[i] !== needle[i]) return false;
        }
        return true;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
indexOf
r1 = (str.indexOf("test") === 0);
r2 = (str.indexOf("not there") === 0);
ready
lastIndexOf
r1 = (str.lastIndexOf("test", 0) === 0);
r2 = (str.lastIndexOf("not there", 0) === 0);
ready
substring
r1 = (str.substring(0, 4) === "test");
r2 = (str.substring(0, 9) === "not there");
ready
slice
r1 = (str.slice(0, 4) === "test");
r2 = (str.slice(0, 9) === "not there");
ready
regex
r1 = (/^test/).test(str);
r2 = (/^not there/).test(str);
ready
Proto startsWith
r1 = str.startsWith('test');
r2 = str.startsWith('not there');
ready
startsWith
r1 = startsWith(str, 'test');
r2 = startsWith(str, 'not there');
ready
startsWithLoop
r1 = startsWithLoop(str, 'test');
r2 = startsWithLoop(str, 'not there');
ready
Proto startsWithLoop
r1 = str.startsWithLoop('test');
r2 = str.startsWithLoop('not there');
ready
Underscore startsWith
r1 = s.startsWith(str, 'test');
r2 = s.startsWith(str, 'not there');
ready

Revisions

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