Zero Padding Numbers

JavaScript performance comparison

Test case created by Brandon Tilley

Info

Testing multiple methods in which you can pad a number with zeros until the string reaches a predetermined length.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function padWhile(num, size) {
      var s = num+"";
      while (s.length < size) s = "0" + s;
      return s;
    }
   
    function padJoin(num, places) {
      var zero = places - num.toString().length + 1;
      return Array(+(zero > 0 && zero)).join("0") + num;
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Pad using While Loop
padWhile(5, 2);
padWhile(5, 4);
padWhile(502, 6);
padWhile(1234, 2);
pending…
Pad using Array#join
padJoin(5, 2);
padJoin(5, 4);
padJoin(502, 6);
padJoin(1234, 2);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment