Tests:
  • Simple for loop

    x
     
    function repeatify(string, repetitions) {
       if (repetitions < 0 || repetitions === Infinity) {
          throw new RangeError('Invalid repetitions number');
       }
     
       let result = '';
     
       for (let i = 0; i < repetitions; i++) {
          result += string;
       }
     
       return result;
    }
    repeatify('*', 10000);
  • Extended for loop

     
    function repeatify2(string, repetitions) {
       if (repetitions < 0 || repetitions === Infinity) {
          throw new RangeError('Invalid repetitions number');
       }
     
       const isEven = repetitions % 2 === 0;
       const iterations = Math.floor(repetitions / 2);
       const stringTwice = string + string;
     
       let result = '';
     
       for (let i = 0; i < iterations; i++) {
          result += stringTwice;
       }
     
       if (!isEven) {
          result += string;
       }
     
       return result;
    }
    repeatify2('*', 10000);
  • Log based

     
    function repeatify3(string, repetitions) {
       if (repetitions < 0 || repetitions === Infinity) {
          throw new RangeError('Invalid repetitions number');
       }
     
       const cache = new Map();
     
       function repeat(string, repetitions) {
          if (repetitions === 0) {
             return '';
          }
     
          const log = Math.floor(Math.log2(repetitions));
          let result;
     
          if (cache.has(log)) {
             result = cache.get(log);
          } else {
             result = string;
     
             for (let i = 1; i <= log; i++) {
                result += result;
                cache.set(i, result);
             }
          }
     
          const repetitionsProcessed = Math.pow(2, log);
          const repetitionsLeft = repetitions - repetitionsProcessed;
     
          return result + repeat(string, repetitionsLeft);
       }
     
       return repeat(string, repetitions);
    }
    repeatify3('*', 10000);
Rendered benchmark preparation results:

Suite status: <idle, ready to run>

Previous results

Experimental features:

  • Test case name Result
    Simple for loop
    Extended for loop
    Log based

    Fastest: N/A

    Slowest: N/A

Latest run results:
Run details: (Test run date: 2 years ago)
Mozilla/5.0 (iPhone; CPU iPhone OS 15_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Mobile/15E148 Safari/604.1
Mobile Safari 15 on iOS 15.3.1
View result in a separate tab
Test name Executions per second
Simple for loop 16449.4 Ops/sec
Extended for loop 32179.8 Ops/sec
Log based 409961.4 Ops/sec