Zero Padding

JavaScript performance comparison

Test case created by Milan Adamovsky

Info

This tests various solutions to front zero pad a number. In my tests I only want to test for a set number of desired number length which is a two digit number (e.g. 2 becomes 02, 10 stays 10).

Preparation code

<script>
  var h = 5;
</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
Ternary Padding (as string)
x = (h < 10) ? ("0" + h) : h;
pending…
Slice() Padding (as string)
x = ("0" + h).slice(-2);
pending…
Slice() Padding (as array)
x = ([0, h].join('')).slice(-2);
pending…
Ternary Padding (as array)
x = (h < 10) ? ([0, h].join('')) : h;
pending…
Function based (complex)
function zeroFill(number, width) {
 width -= number.toString().length;
 if (width > 0) {
  return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
 }
 return number;
}

x = zeroFill(5, 2);
pending…
Function based (simple)
function zeroFill2(num) {
 if (num < 10 && num >= 0) {
  return ["0", num].join("");
 }
 return ["", num].join("");
}

x = zeroFill2(5);
pending…
If Padding
if (h < 10)("0" + h)

x = h;
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:

4 comments

Pau Sanchez commented :

Awesome, is really good to have tests to check performance issues of javascript code right on the browser, available to anyone ;)

Pau Sanchez commented :

As suggested by Ola recently on the thread of my post, here is a piece of code worth considering:

h = 3;
('000' + h.toString()).substr(h.toString().length);

This will produce "003" which is more understandable than other approaches.

Andrei commented :

Error: Benchmark.js was unable to find a working timer..
message: Benchmark.js was unable to find a working timer.

ReferenceError: Undefined variable: a.
message: Undefined variable: a

TypeError: Cannot convert 'aD' to object.
message: Cannot convert 'aD' to object

ReferenceError: Undefined variable: vif.
message: Undefined variable: vif

Version information
Version
11.50

Build
1074

Platform
Win32

System
Windows XP

XHTML+Voice
Plug-in not loaded

Browser identification

Opera/9.80 (Windows NT 5.1; U; en) Presto/2.9.168 Version/11.50

Add a comment