-
-
Save caponica/5621303 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
zfill1 | |
it took 198 | |
zfill2 | |
it took 1160 | |
zfill3 | |
it took 39 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 zfill3(number, places) { | |
return ('000000'+number).slice(-6); | |
} | |
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); | |
console.info("zfill3"); | |
benchit(zfill3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment