HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Efficient string concatenations with DOM

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withefficientconcatenationsdomstring

Problem

I form DOM nodes as strings and append them to DOM tree like below using jQuery.

var dom = 'first name'
             'last name';

$("#contacts").append(dom);


The above code is a small sample. In most of my cases dom will hold big strings.

When I recently read about JS performance tutorials, I saw this post. It mentioned that this way of string concatenation is not a good practice. It mentioned the use of .join() instead of concatenation. That seems like an old post, so which one is efficient in these days?

Solution

Strings are immutable. It means that when you allocate memory while creating a string, you are not able to reallocate it.
So, this code:

var a = 'a';
a = a + 'bc';


Will allocate a new block of memory for 'a' variable, instead of reusing already allocated.

When you do something like 'a' + 'b' + 'c' + 'd' each concatenation allocates a new block of memory for every temporary string.

When you use something like this:

var a = 'a';
a = [a, 'b', 'c'].join('');


join function calculates memory for result string and allocates it only once for a complete string.

As it is shown in the post that you mentioned, it is easier to handle and to avoid memory leaks in JS interpreter (it seems that IE6 and IE7 just not handle garbage collection for the first variant correctly).

If you are interested for the speed of string concatenation for different browsers you can try and view it here.

UPD: Not advocating join, just trying to explain why it was assumed as an optimized variant. As seen at jsPerf tests new browsers optimize string concatenation, so it is faster.

Code Snippets

var a = 'a';
a = a + 'bc';
var a = 'a';
a = [a, 'b', 'c'].join('');

Context

StackExchange Code Review Q#19479, answer score: 13

Revisions (0)

No revisions yet.