left-pad vs array_join vs log_n vs more

JavaScript performance comparison

Revision 2 of this test case created by

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
left-pad
function padString1(str, len, ch) {
  var len = len - str.length;
  var i = -1;
  while (++i < len) {
    str = ch + str;
  }
  return str;
}

for (var i = 0; i < 50000; i++) {
  var str = padString1("hello world", 1000, " ");
}
pending…
array_join
function padString2(str, len, ch) {
  return Array(len + 1 - str.length).join(ch) + str;
}

for (var i = 0; i < 50000; i++) {
  var str = padString2("hello world", 1000, " ");
}
pending…
log_n
function padString3(str, len, ch) {
  str = String(str);

  if (!ch && ch !== 0) ch = ' ';

  len = len - str.length;
  if (len <= 0) return str;

  ch = ch + '';
  var pad = '';
  while (true) {
    if (len & 1) pad += ch;
    len >>= 1;
    if (len) ch += ch;
    else break;
  }
  return pad + str;
}

for (var i = 0; i < 50000; i++) {
  var str = padString3("hello world", 1000, " ");
}
pending…
repeat
function padString4(str, len, ch) {
  str = String(str);
  if (!ch && ch !== 0) ch = ' ';
  var l = len - str.length;
  if (l > 0) return ch.repeat(l) + str;
  return str;
}

for (var i = 0; i < 50000; i++) {
  var str = padString4("hello world", 1000, " ");
}
pending…
repeat_polyfill
String.prototype.repeatPoly = function(count) {

  'use strict';
  if (this == null) {
    throw new TypeError('can\'t convert ' + this + ' to object');
  }
  var str = '' + this;
  count = +count;
  if (count != count) {
    count = 0;
  }
  if (count < 0) {
    throw new RangeError('repeat count must be non-negative');
  }
  if (count == Infinity) {
    throw new RangeError('repeat count must be less than infinity');
  }
  count = Math.floor(count);
  if (str.length == 0 || count == 0) {
    return '';
  }
  // Ensuring count is a 31-bit integer allows us to heavily optimize the
  // main part. But anyway, most current (August 2014) browsers can't handle
  // strings 1 << 28 chars or longer, so:
  if (str.length * count >= 1 << 28) {
    throw new RangeError('repeat count must not overflow maximum string size');
  }
  var rpt = '';
  for (;;) {
    if ((count & 1) == 1) {
      rpt += str;
    }
    count >>>= 1;
    if (count == 0) {
      break;
    }
    str += str;
  }
  // Could we try:
  // return Array(count + 1).join(this);
  return rpt;
}

function padString5(str, len, ch) {
  str = String(str);
  if (!ch && ch !== 0) ch = ' ';
  var l = len - str.length;
  if (l > 0) return ch.repeatPoly(l) + str;
  return str;
}

for (var i = 0; i < 50000; i++) {
  var str = padString5("hello world", 1000, " ");
}
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