Ensure 2 digit numbers

JavaScript performance comparison

Revision 2 of this test case created by mdrob

Info

Quick test for ensuring numnbers (specifically times for countdowns) are always formatted with 2 digits. Slice vs. the usual if n < 10 checks.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var aTest = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
};
</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
Old
function formatOld(aTest) {
  var i = 0,
    l = aTest.length,
    theTest;
  for (; i < l; i++) {
    theTest = aTest[i];
    if (theTest < 10) {
      theTest = '0' + theTest;
    }
  }
}
pending…
New
function formatNew(aTest) {
  var i = 0,
    l = aTest.length,
    theTest;
  for (; i < l; i++) {
    theTest = aTest[i];
    theTest = ('0' + theTest).slice(-2);
  }
}
pending…
stackoverflow test
function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function formatSO(aTest) {
  var i = 0,
    l = aTest.length,
    theTest;
  for (; i < l; i++) {
    theTest = aTest[i];
    if (theTest < 10) {
      theTest = pad(theTest, 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