Skip to content

Instantly share code, notes, and snippets.

@paulownia
Created March 25, 2016 01:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulownia/814b57f4b292b1ba4571 to your computer and use it in GitHub Desktop.
Save paulownia/814b57f4b292b1ba4571 to your computer and use it in GitHub Desktop.
'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