String repetition in javascript
This is about a little snippet I came up with the other month, while a colleague and I were talking about string building and its performance in javascript. I was looking for a neat way to front-pad or indent a string, and missing the 1
x
It turns out there is a succinct, one-line idiom:
var indent = new Array(10).join(" ")
That gets you a 9-spaces-long string. Using the formal Array constructor (rather than the array literal 1
[ ]
1
join
Of course if you already know something about what string you are looking to create here, its definately fastest to declare a long string like
var spacePadding = " ";
and then 1 | var indent = spacePadding.substring(indentLevel) |
»»»»level 1
»»»»»»level 2
Or, worse (or better) if you need to repeat something like 1
<span class="indent">
1
join
var indent = new Array(indentLevel+1).join('<span class="indent">');
You can see the test file I used to time various options. new Array(n).join performs worst when n is a small number - like 20 - and its a short or single character string you are repeating. Frankly, for the use case I’ve outlined - front-padding something - that’s also a likely range. As you scale up, and start repeating 100s or 1000s of times, and also increase the length of the string you are repeating, then this margin disappears.