left-pad vs array_join vs log_n

JavaScript performance comparison

Revision 4 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…
recursive+cache
var makeSpace_cache = [ '' , ' ' , '  ' , '   ' , '    ' ]

function makeSpace( len ){
	var res = makeSpace_cache[ len ]
	if( res !== void 0 ) return res
	
	var cut = len >> 1
	var res = makeSpace( cut )
	res += res
	if( res & 1 ) res += ' '
	
	makeSpace_cache[ len ] = res
	
	return res
}

function padString4 (str, len, ch) {
	return makeSpace( len - str.length ) + str;
}

for (var i=0; i<50000; i++) {
	var str = padString4("hello world", 1000, " ");
}
pending…
duplicates
	
function padString5 (str, len, ch) {
  var pad = ch || ' '
  var needed = len - str.length
  
  var l = 1
  while( l < needed ) {
	  pad += pad
	  l = l << 1
  } 

  return pad.substring( 0 , needed ) + 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