count chars index vs split vs for

JavaScript performance comparison

Test case created by Paul S

Preparation code

<script>
function indexOfMethod(haystack, needle) {
    var total = 0, pos = -1;
    while (-1 !== (pos = haystack.indexOf(needle, pos + 1)))
        total += 1;
    return total;
}
function splitMethod(haystack, needle) {
    return haystack.split(needle).length - 1;
}
function forMethod(haystack, needle) {
    var total = 0, i;
    for (i = 0; i < haystack.length; ++i)
        if (haystack.charAt(i) === needle)
            total += 1;
    return total;
}
var str1 = 'foobarbaz fizzbuzz',
    str2 = 'qwertyuiop asdfghjkl zxcvbnm qwertyuiop asdfghjkl zxcvbnm',
    str3 = str1 + str2 + str1 + str2 + str1 + str2 + str1 + str2 + str1;
</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
indexOf
indexOfMethod(str1, 'b');
indexOfMethod(str2, 'b');
indexOfMethod(str3, 'b');
pending…
split
splitMethod(str1, 'b');
splitMethod(str2, 'b');
splitMethod(str3, 'b');
pending…
for
forMethod(str1, 'b');
forMethod(str2, 'b');
forMethod(str3, 'b');
pending…

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

Compare results of other browsers

0 comments

Add a comment