← Back to context

Comment by nikolay

11 years ago

Allocate and join an array of blanks just to repeat a string is acceptable?!

Joining an array of strings is sometimes better than concatenating a string in place, yes.

Consider the following:

  1: var str = 'foo';
  2: str += 'bar';
  3: str += 'baz';

At program load, you have three string constants, 'foo', 'bar', and 'baz'. At 1, 'str' becomes a pointer to the string constant 'foo'. At 2, 'str' becomes a pointer to a string 'foobar'. Memory is allocated to store this string. At 3, 'str' becomes a pointer to a stinrg 'foobarbaz'. Memory is allocated to store this string.

Now consider the following:

  1: var str = ['foo', 'bar', 'baz'].join('');

At program load, you have three string constants, 'foo', 'bar', and 'baz'. At 1, 'str' becomes a pointer to the string constant 'foobarbaz'. In the array concatenation, the JS interpreter can create a single string buffer large enough to contain the contents of each array element and the separator string * N - 1 (where N is the number of elements), and return a pointer.

Once you have a large number of elements, or are joining large strings, the performance difference (especially regarding garbage collection) could matter.