Ways to 0-pad a number (v4)

Revision 4 of this benchmark created by Michael A. Smith on


Description

There are lots of ways to zero-pad a number in JavaScript. Which is fastest?

This edition tries to optimize the functions without changing their algorithms.

Setup

/**
     * Pad a number with leading zeros to "pad" places:
     *
     * @param n: The number to pad
     * @param l: The maximum number of leading zeros
     */
    function padMath(n, l) {
        var x = +("1E" + l); // 10^l
        return n < x ? ("" + (x + n)).substr(1) : "" + n
    }
    function padLoop(n, l) {
        var s = '' + n;
        while (s.length < l) {
            s = '0' + s;
        }
        return s;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Math
padMath(1301, 4);
padMath(120, 4);
padMath(14, 4);
padMath(9, 4);
 
ready
Loop
padLoop(1301, 4);
padLoop(120, 4);
padLoop(14, 4);
padLoop(9, 4);
 
ready

Revisions

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