Ultimate Performance Test - Count the number of characters in a string in JavaScript

Benchmark created by Lorenz Lo Sauer on


Setup

//from 'is-lib' https://github.com/lsauer/is-library
  str2buffer = function(s) {
    var bu = new ArrayBuffer(s.length),
      aUint8 = new Uint8Array(bu);
  }

Test runner

Ready to run.

Testing in
TestOps/sec
regex based
("this is foo bar".match(/o/g) || []).length;
ready
splitting the string
"this is foo bar".split("o").length - 1;
ready
using indexOf
var stringsearch = "o", str = "this is foo bar";
for (var count = -1, index = 0; index != -1; count++, index = str.indexOf(stringsearch, index + 1));
count;
ready
searching for a single character
var stringsearch = "o",
  str = "this is foo bar";
for (var i = count = 0; i < str.length; count += +(stringsearch === str[i++]));
count;
ready
element mapping and filtering;
var str = "this is foo bar";
var counts = str.split('').map(function(e, i) {
  if (e === 'o') return i;
})
  .filter(Boolean);
counts.length;
ready
'deleting' the character out of the string
var str = "this is foo bar";
str.length - str.replace(/o/g, '').length;
ready
based on typed arrays
str2buffer = function(s) {
  var bu = new ArrayBuffer(s.length),
    aUint8 = new Uint8Array(bu);
  for (var i = 0; i < bu.byteLength; aUint8[i] = s.charCodeAt(i), i++);
  return aUint8;
};
var bstr = str2buffer("this is foo bar"),
  schar = 'o'.charCodeAt(),
  cnt = 0;
for (var i = 0; i < bstr.byteLength; schar !== bstr[i++] || cnt++);
cnt;
ready
based on untyped Arrays
var ubstr = "this is foo bar".split('').map(function(e, i) {
  return e.charCodeAt();
})
//>[116, 104, 105, 115, 32, 105, 115, 32, 102, 111, 111, 32, 98, 97, 114]
  ,
  schar = 'o'.charCodeAt(),
  cnt = 0;
for (var i = 0; i < ubstr.length; schar !== ubstr[i++] || cnt++);
cnt;
ready
using reduce.
var str = "this is foo bar",
  schar = 'o';
str.split('').reduce(
  function(p, c, i, a) {
    if (c === schar || p === schar) {
      return isNaN(parseInt(p)) ? 1 : +p + 1;
    }
    return p;
  }
)
ready
dictionary character histogram
var str = "this is foo bar",
  schar = 'o',
  hist = {};
for (si in str) {
  hist[str[si]] = hist[str[si]] ? 1 + hist[str[si]] : 1;
};
hist[schar];
ready

Revisions

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

  • Revision 1: published by Lorenz Lo Sauer on
  • Revision 7: published by Simon on
  • Revision 9: published by Bruno G. on