String Repeat - Recursion vs. For Loop

JavaScript performance comparison

Test case created by connrs

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function loopStringRepeat(str, num) {
    var result = '';
    for (; num > 0; num >>>= 1) { // (1)
      if (num & 1) { // (2)
        result += str;
      }
      str += str;
    }
  
    return result;
  }
  
  function recursiveStringRepeat(num, str) {
      if (num === 0) return '';
      return recursiveStringRepeat(num >>> 1, str + str) + (num & 1 ? str : '');
  }

};
</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
loopStringRepeat('abcdefghijklmnopqrstuvwxyz', 2000000);
pending…
Recursion
recursiveStringRepeat(2000000, 'abcdefghijklmnopqrstuvwxyz');
pending…

Compare results of other browsers

Revisions

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

0 Comments