Count number of occurrences of a character in a string (v5)

Revision 5 of this benchmark created on


Setup

if (!window.setupDefined) {
  
  window.setupDefined = true;
  
  window.gen_str = function (count) {
      var result = '',
          alpha = 'zxcvbnm,./\\\';lkjhgfdsaqwertyuiop[]<>?|":}{+_)(*&^%$#@!~`1234567890-=';
  
      while (result.length < count) {
          result = result.concat(Math.random().toString(36).slice(2));
      }
  
      result = result.slice(result.length - count);
  
      return result;
  };
  
  window.gen_str2 = function (count) {
      var result = '',
          alpha = 'zxcvbnm,./\\\';lkjhgfdsaqwertyuiop[]<>?|":}{+_)(*&^%$#@!~`1234567890-=',
          i;
  
      for (i = 0; i < count; i += 1) {
          result = result.concat(alpha[Math.floor(Math.random() * alpha.length)]);
      }
  
      return result;
  };
  
  window.get_timer = function (sstart) {
      var tstart = (new Date()).getTime();
  
      return function (send) {
          console.log(sstart + ((new Date()).getTime() - tstart) / 1000 + send);
      };
  };
  
  window.count_split = function (str, schar) {
      return str.split(schar).length - 1;
  };
  
  window.count_for = function (str,schar) {
      var count = 0,
          i;
  
      for (i = 0; i < str.length; i += 1) {
          if(str[i] === schar) {
              count += 1;
          }
      }
  
      return count;
  };
  
  window.count_replace = function (str, schar) {
      return str.length - str.replace(RegExp(schar, 'g'), '').length;
  };
  
  window.count_match = function (str, schar) {
      return str.match(RegExp(schar, 'g')).length;
  };
  
  window.count_indexOf = function(str, schar) {
      var count = 0, i = 0;
  
      while (i < str.length) {    
         i = str.indexOf(schar, i);
         if (i === -1) break;
         count++;
         i++;
      }
  
      return count;
  };
  
  window.stringToTest = gen_str(1 * 1000 * 1000);
  
  } // End-of: if (!window.setupDefined) {

Test runner

Ready to run.

Testing in
TestOps/sec
count_split
window.count_split(window.stringToTest, 'a');
ready
count_for
window.count_for(window.stringToTest, 'a');
ready
count_replace
window.count_replace(window.stringToTest, 'a');
ready
count_match
window.count_match(window.stringToTest, 'a');
ready
count_indexOf
window.count_indexOf(window.stringToTest, 'a');
ready

Revisions

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