Native String#startsWith Short + Invalid Matches

JavaScript performance comparison

Revision 10 of this test case created by MB

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var longString1 = 'Lorem ipsum dolor sit';
    var longString2 = 'Dorem ipsum dolor sit';
   
    var strToMatch = 'Lorem';
   
    function startsWith1(longString1, longString2, strToMatch) {
        return longString1.slice(0, strToMatch.length) === strToMatch
    && longString2.slice(0, strToMatch.length) === strToMatch;
    }
   
    function startsWith2(longString1, longString2, strToMatch) {
        return longString1.indexOf(strToMatch) === 0
    && longString2.indexOf(strToMatch) === 0;
    }
   
    function startsWith3(longString1, longString2, strToMatch) {
        return longString1.lastIndexOf(strToMatch, 0) === 0
    && longString2.lastIndexOf(strToMatch, 0) === 0;
    }
   
    function startsWith4(longString1, longString2, strToMatch) {
    var x = true;
        for (var i = 0, j = strToMatch.length - 1; i < j; i++, j--) {
            if (strToMatch.charAt(i) != longString1.charAt(i) || strToMatch.charAt(j) != longString1.charAt(j)) {
                x = false;
            }
        }
        for (var i = 0, j = strToMatch.length - 1; i < j; i++, j--) {
            if (strToMatch.charAt(i) != longString2.charAt(i) || strToMatch.charAt(j) != longString2.charAt(j)) {
                x = false;
            }
        }
        return x;
    }
};
</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
Slice
startsWith1(longString1, longString2, strToMatch)
pending…
indexOf
startsWith2(longString1, longString2, strToMatch)
pending…
lastIndexOf
startsWith3(longString1, longString2, strToMatch)
pending…
Loop
startsWith4(longString1, longString2, strToMatch)
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