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

operator in perl.

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

[ ]
) you can specify what the initial size or length of the array should be, and we leverage that when joining our otherwise empty array. The string we provide to
with ends up being repeated n-1 times. Cute huh. It also turns out to be pretty fast. Not quite as fast as the equivalent loop using += to build the string, but much faster in many cases than pushing each character into an array and joining to produce the string.

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
var indent = spacePadding.substring(indentLevel)
, and cross your fingers that spacePadding will always be long enough. That’s going to be a pain, though, when you need to output something like
»»»»level 1
»»»»»»level 2

Or, worse (or better) if you need to repeat something like

<span class="indent">
. Its trivial with our

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.