indexOf or loop to find char

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // 500-character random alphanumeric string.
    var haystack = 'gWkfGnHA0XyxkHQVVyDlBuPLzUfBqdWMrr3y470wbfmR4th66ZWI1SjNzsCpPLRlySGo5P6pAl0Wk3RYuJc2e0FA1r6RnVIPcTHdrb3I1sB97wSokAy0YQ4Oq4uvcdPOKVD1aeiWjxITyaOlPDw6KKFsJqUOlj7zo9gvIQaI1UvIL1dU1D3UAvB5fGzmGyWETwo6wZ1njFDSYmJEQWJThCAoqTs3lgvlb5LPOvCHkoJnhJp2i85a42VsVmcyBcjziiCHOPxwYr9OqVKLaIq1jimrBxBWfEQe8dR3R2NQaffP1PziBTCciuUB3DjpavVPEIYlwMHy7aYL5FkfbfoM6D14Ql3gj9TAkY3xWd2YCzxzIFZvKmf1DXTbEyyYMKnjvvPWHa4nMcUxeNMbOR5QANkWlaXdFHceySSbuXHzxMAISyDsVpW5dmQbY5LWHEwKtJNZbyIKn62X4tYlsYBbQOy2pbLMS8X1TYAyXItMyWvFIayR96oQ';
   
    var foundIndices = [];
};
</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
for (var i = 0; i < haystack.length; i++) {
    i = haystack.indexOf('a', i);
    if (i == -1) {
      break;
    }
    foundIndices.push(i);
  }
pending…
loop
for (var i = 0; i < haystack.length; i++) {
  if (haystack.charAt(i) == 'a') {
    foundIndices.push(i);
  }
}
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