Zero Padding Numbers

JavaScript performance comparison

Revision 2 of this test case created

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 padWhile2(num, size) {
      num = num+"";
      while (num.length < size) num = "0" + num;
      return num;
    }
   
    function padJoin(num, places) {
      var zero = places - num.toString().length + 1;
      return Array(+(zero > 0 && zero)).join("0") + num;
    }
   
    function padRecursive(num, places) {
      num=num+"";
      return num.length >= places ? num : padRecursive("0" + num, places);
    }
   
    function padRecursive2(num, places) {
      return num.toString().length >= places ? num : padRecursive2("0" + num, places);
    }
   
    function padSubstring(num,places){
      num=num+"";
      return num.length >= places ? num : ('000000000000000000000000000000000000000000000' + num).substr(-places);
    }
};
</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…
Pad Recursive
padRecursive(5, 2);
padRecursive(5, 4);
padRecursive(502, 6);
padRecursive(1234, 2);
pending…
Pad Recursive toString()
padRecursive2(5, 2);
padRecursive2(5, 4);
padRecursive2(502, 6);
padRecursive2(1234, 2);
pending…
Pad Substring
padSubstring(5, 2);
padSubstring(5, 4);
padSubstring(502, 6);
padSubstring(1234, 2);
pending…
Pad While without var s
padWhile2(5, 2);
padWhile2(5, 4);
padWhile2(502, 6);
padWhile2(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