Ways to 0-pad a number
JavaScript performance comparison
Info
There are lots of ways to zero-pad a number in JavaScript. Which is fastest?
Preparation code
<script>
Benchmark.prototype.setup = function() {
/**
* Pad a number with leading zeros to "pad" places:
*
* @param number: The number to pad
* @param pad: The maximum number of leading zeros
*/
function padNumberMath(number, pad) {
var N = Math.pow(10, pad);
return number < N ? ("" + (N + number)).slice(1) : "" + number
}
function padNumberArray(n, len) {
return (new Array(len + 1).join('0') + n).slice(-len);
}
function padNumberLoop(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Math |
|
pending… |
Array join |
|
pending… |
Loop |
|
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:
- Revision 1: published by Michael A. Smith
- Revision 2: published by Michael A. Smith
- Revision 3: published by wolever
- Revision 4: published by Michael A. Smith
- Revision 5: published by billy
- Revision 6: published by Michael A. Smith
- Revision 7: published by billy
- Revision 8: published
- Revision 9: published by Vasil Dimov
- Revision 10: published by Marcel Duran and last updated
- Revision 11: published by TNO
- Revision 13: published by p3k
1 comment
Wow, that's crazy. IE in 64-bit mode does the loop faster. In 32-bit mode it does the Math faster. What gives?