Count the number of occurrences in string (v27)

Revision 27 of this benchmark created by Sam on


Description

Count the occurrences of a single character in a string.

Setup

var matcher = /e/g;
    var testString = "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence,promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.";

Test runner

Ready to run.

Testing in
TestOps/sec
regular expression
testString.match(matcher).length;
ready
split
testString.split("e").length - 1;
ready
iterate
var count = 0;
for (var i = 0; i < testString.length; i++) {
   if (testString.charAt(i) === "e") {
      count += 1;
   }
}
ready
while
var count = 0;
while (testString.length) {
  if (testString.charAt(0) === "e") {
      count += 1;
   }
   testString = testString.slice(1);
}
ready
for
var count = 0;
for (var i = 0, size = testString.length; i < size; i++) {
   if (testString.charAt(i) === "e") {
      count++;
   }
}
ready
indexOf
var count = 0;
var last_index = -1;

while(true) {
    last_index = testString.indexOf('e', last_index + 1);

    if(last_index === -1) {
        break;
    }

    ++count;
}
ready

Revisions

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