Zerofill with array vs while

Benchmark created by Grubshka on


Description

I saw http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript and I was just curious about performances.

Preparation HTML

<script>
  function zeroFill_Array(number, width) {
   var str = number.toString();
   var remWidth = width - str.length;
   if (remWidth > 0) {
    return new Array(remWidth + (/\./.test(str) ? 2 : 1)).join('0') + str;
   }
   return str;
  }
  
  function zeroFill_While(number, width) {
   var str = number.toString();
   var remWidth = width - str.length;
   while (--remWidth >= 0) {
    str = "0" + str;
   }
   return str;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Zerofill_array 5
zeroFill_Array(5, 5);
ready
Zerofill_while 5
zeroFill_While(5, 5);
ready
Zerofill_array 100
zeroFill_Array(5, 100);
ready
Zerofill_while 100
zeroFill_While(5, 100);
ready
Zerofill_array 10000
zeroFill_Array(5, 10000);
ready
Zerofill_while 10000
zeroFill_While(5, 10000);
ready

Revisions

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

  • Revision 1: published by Grubshka on