String Concatenation vs. Array.join

by Geethalakshmi 2010-09-16 21:19:58

String Concatenation vs. Array.join


This cannot be stressed enough, doing many string concatenation operations can be a major hit on performance, and it's easy to avoid in many situations. Consider for example that you want to build a string out of many pieces, one bad way to do this is using the + to concatenate all pieces into a huge string, one piece at a time:

str = '';
for (/* each piece */) {
str += piece; // bad for performance!
}
return str;


This method will result in too many intermediate strings and concatenation operations, and will poorly perform overall.

A better approach to this problem is using Array.join(), this method joins all array elements into one string:

var tmp = [];
for (/* each piece */) {
tmp.push(piece);
}
str = tmp.join(''); // Specified an empty separator, thanks Jonathan
return str;


This method doesn't suffer from the extra string objects, and generally executes faster.

Tagged in:

1065
like
0
dislike
0
mail
flag

You must LOGIN to add comments