jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
There are lots of ways to zero-pad a number in JavaScript. Which is fastest?
CHANGELOG: Modern browsers handle for-loops very well so I added a for-loop
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<script src="http://epeli.github.io/underscore.string/dist/underscore.string.min.js"></script>
/**
* 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) {
var n_str = n.toString();
if (n_str.length >= len) {
return (n_str);
}
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;
}
function padNumberForLoop(number, length) {
var my_string = '' + number;
for (var i=0,endi=length-my_string.length;i < endi;i++) {
my_string = '0' + my_string;
}
return my_string;
}
// padStr is the zero-pad string, e.g.: "0000"
function padNumberString(number, padStr) {
var len = padStr.length;
number = number.toString();
return number.length >= len ? number : (padStr + number).slice(-len);
}
function padRec(str, ch, len) {
return str.length >= len ? str : padRec(ch + str, ch, len);
}
function padSplitWhileUnshiftJoin(number, len) {
var result = String(number).split('');
while (result.length < len) {
result.unshift(0);
}
return result.join('');
}
_.mixin(_.str.exports());
function padWithUnderscoreString(number, len) {
return _.pad(number, len, '0');
}
function padWhile(num, count) {
var pad = count - (num + '').length;
while(--pad > -1) {
num = '0' + num;
}
return num;
};
String.prototype.padLeft = function(ch, len){
return this.length >= len ? this : (ch + this).padLeft(ch, len)
}
Ready to run.
Test | Ops/sec | |
---|---|---|
Math |
| ready |
Array join |
| ready |
Loop |
| ready |
String Pad |
| ready |
Recursive |
| ready |
Split-While-Unshift-Join |
| ready |
Pad with Underscore.string |
| ready |
Pad while |
| ready |
OO-Recursive |
| ready |
For Loop |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.