Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Last active May 17, 2023 01:54
Show Gist options
  • Save tallpeak/b6455e02100ca929d297c1ad118c5a59 to your computer and use it in GitHub Desktop.
Save tallpeak/b6455e02100ca929d297c1ad118c5a59 to your computer and use it in GitHub Desktop.
function leftPad(str, len, ch) {
str = String(str);
var i=-1;
if (!ch && ch != 0) ch=' ';
len -= str.length;
while (++i<len) {
str = ch + str;
}
return str;
}
function leftPadP(str,len,ch) {
return new Array(len-str.length).fill(!ch&&ch!=0?' ':ch).join("")+str
}
function leftPadP2(str,len,ch) {
return new Array(len-str.length).join(!ch&&ch!=0?' ':ch)+str
}
new Array(42).join(' ')
function leftPadA(str, len, ch) {
s = "";
var i=-1;
if (!ch && ch != 0) ch=' ';
len -= str.length;
while (++i<len) {
s += ch;
}
return s + String(str);
}
function leftPadA2(str, len, ch)
{
return str.padStart(len, !ch&&ch!=0?' ':ch);
}
function run(fn, count, ...args) {
const start = performance.now();
for (i=0;i<count;++i) {
ret = fn.apply(null,args);
//console.log(ret);
}
return performance.now()-start;
}
console.log("loops","spaces","leftPad(orig)","Prime ", "Prime2 ", "Aaron ","padStart");
[100,1000].forEach(x=> {
[100,1000,10000,100000].forEach(y=> {
console.log(x.toString().padStart(5),y.toString().padStart(6),
run(leftPad,x,'foo',y).toFixed(3).padStart(9),
run(leftPadP,x,'foo',y).toFixed(3).padStart(9),
run(leftPadP2,x,'foo',y).toFixed(3).padStart(9),
run(leftPadA,x,'foo',y).toFixed(3).padStart(9),
run(leftPadA2,x,'foo',y).toFixed(3).padStart(9),
);
});
});
@tallpeak
Copy link
Author

tallpeak commented May 17, 2023

nodejs v19.7.0, AMD 5625U laptop
node .\leftPad_time.js
loops spaces leftPad(orig) Prime   Prime2    Aaron    padStart
  100    100     1.239     0.396     0.615     0.621     0.237
  100   1000     1.123     1.482     0.528     1.348     0.015
  100  10000    11.119    17.642     5.044    16.160     0.016
  100 100000   111.831   319.022    75.449   223.784     0.020
 1000    100     2.633     1.767     0.762     1.225     0.112
 1000   1000     4.382    17.806     6.985    13.442     0.240
 1000  10000    47.784   172.958    60.518   132.750     0.118
 1000 100000  1298.322  3350.577   790.705  2402.140     0.121

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment