Math vs Bits vs Array

Edit on GitHub

Repeating Strings from https://jsperf.com/js-repeating-strings

Setup

Tests

  • Math

    function math(str, n) {
      var ret = '';
    
      do {
        if (n % 2) {
          ret += str;
        }
    
        n = Math.floor(n / 2);
        str += str;
      } while (n > 0);
      return ret;
    };
    math('unicorn ', 100);
  • Bits

    function bits(str, n) {
      var ret = '';
      do {
        if (n & 1) ret += str;
        str += str;
      } while (n = n >> 1);
      return ret;
    }
    bits('unicorn ', 100);
  • Array

    function array(str, n) {
      (new Array(n + 1)).join(str);
    };
    array('unicorn ', 100);