Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'use strict';
function leftpad1(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 leftpad2(str, len, ch) {
str = String(str);
if (!ch && ch !== 0) ch = ' ';
return String(ch).repeat(len).substring(str.length) + str;
}
function leftpad3(str, len, ch) {
str = String(str);
var i = -1;
if (!ch && ch !== 0) ch = ' ';
len = len - str.length;
if (len > 0) {
var arr = new Array(len);
arr.fill(ch);
return arr.join('') + str;
} else {
return str;
}
}
const len = parseInt(process.argv[2], 10);
const count = 1000000;
console.log("pad length", len);
console.time('concat with +');
for (let i = 0; i < count; i++) {
leftpad1('aaaa', len, 0);
}
console.timeEnd('concat with +');
console.time('repeat substring');
for (let i = 0; i < count; i++) {
leftpad2('aaaa', len, 0);
}
console.timeEnd('repeat substring');
console.time('array fill and join');
for (let i = 0; i < count; i++) {
leftpad3('aaaa', len, 0);
}
console.timeEnd('array fill and join');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.