The ultimate leftpad benchmark

Benchmark created by Paolo on


Description

Comparing FIVE leftpad implementations!

while: complexity with ropes O(n), without O(n^2). memory usage O(n)

Russian peasant: complexity with ropes O(log n), without O(n). memory usage O(log n) to O(n) depending on the implementation

join (there's two of them): complexity O(n), memory usage O(n)

repeat: complexity depends on VM implementation, memory usage too. could be the same as the Russian peasant algorithm or the same as while, but more optimized

Test runner

Ready to run.

Testing in
TestOps/sec
while
var str = "some string here";
var ch = " ";
var len = 150;

var i = -1;
new_str = str;

len = len - str.length;

while (++i < len) {
  new_str = ch + new_str;
}

if (new_str.charCodeAt(149) !== 101) throw new Error(new_str)
 
ready
Russian peasant
var str = "some string here";
var ch = " ";
var len = 150;

new_str = str
for (len = len - str.length;; len >>= 1) {
  if (len & 1) new_str = ch + new_str;
  if (len > 1) ch = ch + ch;
  else break;
}

if (new_str.charCodeAt(149) !== 101) throw new Error(new_str)
 
ready
push and join
var str = "some string here";
var ch = " ";
var len = 150;

var arr = [];
for (var i = 0; i < len - str.length; i++)
  arr.push(ch);
arr.push(str);
new_str = arr.join('');

if (new_str.charCodeAt(149) !== 101) throw new Error(new_str)
 
ready
join empty
var str = "some string here";
var ch = " ";
var len = 150;

new_str = Array(len + 1 - str.length).join(ch) + str;

if (new_str.charCodeAt(149) !== 101) throw new Error(new_str)
 
ready
repeat
var str = "some string here";
var ch = " ";
var len = 150;

new_str = ch.repeat(Math.max(len - str.length, 0)) + str;

if (new_str.charCodeAt(149) !== 101) throw new Error(new_str)
 
ready

Revisions

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