Created
March 25, 2016 01:35
-
-
Save paulownia/814b57f4b292b1ba4571 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
'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