String padding performance

JavaScript performance comparison

Revision 12 of this test case created by Bruno Bronosky

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var t = new Date(),
    i = 0,
    N = 1000000,
    str = '123',
    pad = '0',
    prePadded = '000000000000000000000000000000', // 30 long pre-padded string
    length = 30;
  // prePadded = '00000', // 5 long pre-padded string
  // length = 5;
  
  function padString1(len, pad, str, leftPadded) {
    if (str == undefined) return Array(len - 1).join(pad);
    if (leftPadded) {
      return Array(len + 1 - str.length).join(pad) + str;
    } else {
      return str + Array(len + 1 - str.toString().length).join(pad);
    }
  }
  
  function padString2(len, pad, str, leftPadded) {
    if (str == undefined) str = ''
    if (leftPadded) {
      while (str.length < length) str = pad + str;
    } else {
      while (str.length < length) str = str + pad;
    }
    return str;
  }
  
  function padString3(pad, str, leftPadded) {
    if (str == undefined) return pad;
    if (leftPadded) {
      return (pad + str).slice(-pad.length);
    } else {
      return (str + pad).substring(0, pad.length);
    }
  }
  
  function padString4(padding, str, position) {
    if (typeof str === 'undefined')
      return padding;
  
    if (position < 0) {
      return padding.substring(0, padding.length - str.length) + str;
    } else if (position > 0) {
      return str + padding.slice(-padding.length + str.length);
    } else {
      return pad(padding, pad(padding.substring(0,(Math.ceil(padding.length/2+(padding.length%2!=0 && str.length%2==0 ? 0 : 1)))), str, -1), 1)
    }}
  

};
</script>

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
With a pre-padded buffer string
padString4(prePadded, str, 1);
        padString4(prePadded, undefined, 1);
        padString4(prePadded, str, -1);
pending…

Revisions

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

0 Comments