Repeat characters of a string a specific number of times

JavaScript performance comparison

Test case created by arash16

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var nn = [1, 10, 100, 1000, 10000, 100000];
  var str = 'abc'.repeat(5);
  

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
For loop with push
function repeatBy(str) {
  return function(cnt) {
    var r = [];
    for (var i=0; i<str.length; i++)
      for (var j=0; j<cnt; ++j)
        r.push(str[i]);
    return r;
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…
For loop with assignment
function repeatBy(str) {
  return function(cnt) {
    var r = [];
    for (var i=0; i<str.length; i++)
      for (var j=0; j<cnt; ++j)
        r[i+j] = str[i];
    return r;
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…
split, fill, reduce, spread
function repeatBy(str) {
  var s = str.split('');
  return function(cnt) {
    return s
      .reduce((a, c) => [...a, ...Array(cnt).fill(c)], [])
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…
split, fill, reduce, concat
function repeatBy(str) {
  var s = str.split('');
  return function(cnt) {
    return s
      .reduce((a, c) => a.concat(Array(cnt).fill(c)), [])
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…
split, map, fill, reduce, concat
function repeatBy(str) {
  var s = str.split('');
  return function(cnt) {
    return s
      .map(c => Array(cnt).fill(c))
      .reduce((a, b) => a.concat(b), [])
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…
string replace with regex
function repeatBy(str) {
  return function(cnt) {
    return str.replace(/./g, c => c.repeat(cnt)).split('');
  };
}

var repeatStr = repeatBy(str);
for (var i=0; i<nn.length; ++i)
  repeatStr(nn[i]);
pending…

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

Compare results of other browsers

0 Comments