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

Revision 7 of this benchmark created by Simon on


Description

Demonstrate the performance of obtaining the frequency of a specified character in a given string through hypothetical test cases of various implementations. These tests differ somewhat in the level of additional information obtained.

Setup

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

Test runner

Ready to run.

Testing in
TestOps/sec
regex based
(str.match(/x/g) || []).length;
ready
splitting the string
str.split(stringsearch).length - 1;
ready
using indexOf
for (var count = -1, index = 0; index != -1; count++, index = str.indexOf(stringsearch, index + 1));
count;
ready
searching for a single character
for (var i = count = 0; i < str.length; count += +(stringsearch === str[i++]));
count;
ready
element mapping and filtering;
var counts = str.split('').map(function(e, i) {
  if (e === stringsearch) return i;
})
  .filter(Boolean);
counts.length;
ready
'deleting' the character out of the string
str.length - str.replace(/x/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(str),
  schar = stringsearch.charCodeAt(),
  cnt = 0;
for (var i = 0; i < bstr.byteLength; schar !== bstr[i++] || cnt++);
cnt;
ready
based on untyped Arrays
var ubstr = str.split('').map(function(e, i) {
  return e.charCodeAt();
})
//>[116, 104, 105, 115, 32, 105, 115, 32, 102, 111, 111, 32, 98, 97, 114]
  ,
  schar = stringsearch.charCodeAt(),
  cnt = 0;
for (var i = 0; i < ubstr.length; schar !== ubstr[i++] || cnt++);
cnt;
ready
using reduce.
var schar = stringsearch;
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 schar = stringsearch,
  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