public
Created

benchmarking a couple zfill implementations in node

  • Download Gist
output.txt
1 2 3 4
zfill1
it took 149
zfill2
it took 629
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
function zfill1(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
 
function zfill2(number, places) {
number = number.toString();
var zero = places - number.length + 1;
return new Array(+(zero > 0 && zero)).join("0") + number;
}
 
function time(cb) {
var begin = new Date();
cb();
var end = new Date();
console.info("it took", end - begin);
}
 
function benchit(fn) {
time(function() {
for (var i = 0; i < 100000; ++i) {
var size = Math.floor(Math.random() * 100);
fn(i, size);
}
});
}
 
console.info("zfill1");
benchit(zfill1);
console.info("zfill2");
benchit(zfill2);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.