Skip to content

Instantly share code, notes, and snippets.

@NathanHuisman
Last active May 2, 2023 22:44
Show Gist options
  • Save NathanHuisman/33c73cdfbcb6809a388fd5f2ef83c035 to your computer and use it in GitHub Desktop.
Save NathanHuisman/33c73cdfbcb6809a388fd5f2ef83c035 to your computer and use it in GitHub Desktop.
function leftPad1(str, len, ch) {
return new Array(len - str.length).fill(!ch && ch !== 0 ? ' ' : ch).join("") + str;
}
function leftPad2(str, len, ch) {
str = String(str);
var i = -1;
if (!ch && ch !== 0) ch = ' ';
len = len - str.length;
while (++i < len) {
str = ch + str
}
return str;
}
function leftPad3(str, len, ch) {
ch = (!ch && ch !== 0) ? ' ' : ch;
return ch.repeat(Math.max(0, len - str.length)) + str
}
function native(str, len, ch) {
return str.padStart(len, ch)
}
function bench(fn, count, ...args) {
const start = performance.now();
for (let i = 0; i < count; i++) {
fn.apply(null, args);
}
return performance.now() - start;
}
for (count of [10, 100, 1000, 10000, 1e5, 1e6, 1e7]) {
console.log(`Count = ${count}:`);
console.log("leftPad1", bench(leftPad1, count, "this is a test", 20, ' '));
console.log("leftPad2", bench(leftPad2, count, "this is a test", 20, ' '));
console.log("leftPad3", bench(leftPad3, count, "this is a test", 20, ' '));
console.log("native", bench(native, count, "this is a test", 20, ' '));
}
❯ node bench_leftpad.js
Count = 10:
leftPad1 0.127251997590065
leftPad2 0.054412998259067535
leftPad3 0.054159000515937805
native 0.03197299689054489
Count = 100:
leftPad1 0.05971500277519226
leftPad2 0.04181400686502457
leftPad3 0.03660700470209122
native 0.02214200049638748
Count = 1000:
leftPad1 0.46420199424028397
leftPad2 0.2710139974951744
leftPad3 0.2010589987039566
native 0.6572990044951439
Count = 10000:
leftPad1 4.333123996853828
leftPad2 1.7057819962501526
leftPad3 1.6612680032849312
native 2.011845998466015
Count = 100000:
leftPad1 26.133474998176098
leftPad2 6.151236996054649
leftPad3 6.505015000700951
native 7.053138002753258
Count = 1000000:
leftPad1 260.59084099531174
leftPad2 60.81603699922562
leftPad3 63.255487002432346
native 65.47346600145102
Count = 10000000:
leftPad1 2618.2492320016026
leftPad2 601.4929099977016
leftPad3 630.317967005074
native 655.8400309979916
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment