String Repeat Algorithms (v4)

Revision 4 of this benchmark created on


Description

Checks performance of various string repeat algorithms

Setup

var expected = new Array(950).join('foo');
    
    function bitShift(str, n) {
      if (n < 1) return '';
      var result = '';
      while (n > 0) {
        if (n & 1) result += str;
        n >>= 1;
        str += str;
      }
      return result;
    }
    
    function concat(str, n) {
      var result = '';
      while (n-- > 0) {
        result += str;
      }
      return result;
    }
    
    function join(str, n) {
      return new Array(n + 1).join(str);
    }
    
    function push(str, n) {
      var  arr = [];
      while (n-- > 0) {
        arr.push(str);
      }
      return arr.join('');
    }
    
    var _join = [].join;
    function join2(str, n) {
      return _join.call({length: n + 1}, str);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Regular string concatenation
if (concat('foo', 949) !== expected) {
  throw new Error('Invalid');
}
ready
Join array with empty values
if (join('foo', 949) !== expected) {
  throw new Error('Invalid');
}
ready
Join prepopulated array
if (push('foo', 949) !== expected) {
  throw new Error('Invalid');
}
ready
Special bit shifting algorithm
if (bitShift('foo', 949) !== expected) {
  throw new Error('Invalid');
}
ready
Join 2
if (join2('foo', 949) !== expected) {
  throw new Error('Invalid');
}
ready

Revisions

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