Count the number of occurrences in string (v17)

Revision 17 of this benchmark created by Meryn Stol on


Description

Count the occurrences of a single character in a string.

Setup

var loremIpsumLines = [
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    "Nam eu facilisis ante.",  
    "Proin vel massa nec nisl lobortis eleifend id a lectus.",  
    "Cras dictum sollicitudin magna, eu ultricies sapien congue quis.",  
    "Suspendisse potenti. Morbi ac orci diam. Cras aliquam, magna in suscipit volutpat, velit dui iaculis purus, in elementum risus arcu ut metus.",  
    "Etiam adipiscing tincidunt arcu ac faucibus. Etiam aliquet, velit non auctor consequat, odio nunc malesuada massa, id consequat lacus nunc a est.",
    "Suspendisse pulvinar velit et neque facilisis quis congue nisl rhoncus. Pellentesque auctor iaculis orci ornare congue.",
    "Nam in nunc eros, quis condimentum turpis. In commodo, velit quis laoreet iaculis, mi leo commodo dolor, sit amet pretium libero tellus et massa."];
    
    var loremIpsum = loremIpsumLines.join("\n");
    i=5
    while(i--) loremIpsum = loremIpsum + loremIpsum;
    
    var matcher = /\n/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.";
    var testString = loremIpsum

Test runner

Ready to run.

Testing in
TestOps/sec
RegExp.match
testString.match(matcher).length;
ready
string.split
testString.split("\n").length - 1;
ready
iterate charAt: 0->length
var count = 0;
for (var i = 0; i < testString.length; i++) {
   if (testString.charAt(i) === "\n") {
      count += 1;
   }
}
ready
iterate & slice
var count = 0;
var testStr = testString;

while (testStr.length) {
  if (testStr.charAt(0) === "\n") {
      count += 1;
   }
   testStr = testStr.slice(1);
}
ready
iterate ===: 0->length
var count = 0;
for (var i = 0; i < testString.length; i++) {
   if (testString[i] === "\n") {
      count += 1;
   }
}
ready
With Ints
var count = 0;
var e = "\n" + 0
for (var i = 0; i < testString.length; i++) {
   if ((testString[i] + 0) === e) {
      count += 1;
   }
}
ready

Revisions

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