Efficient building of large strings in JavascriptIf you need to build up a large string in Javascript, there is a right way and a wrong way to do this. The wrong way is to repeatedly concatenate new pieces of the text to the string. The right way is to build up an array with all of the string pieces as array elements and to then join the array into a string when all of the pieces are added. The array method is much faster due to the slow handling of large strings in Javascript.
To illustrate, here's the wrong way to create a string made up of component strings.
...
var result = ;
for ( --some loop condition-- ) {
result += --some string content--;
}
...
And here is the faster way to build up the string
...
var tmpArray = [];
for ( --some loop condition-- ) {
tmpArray.push(--some string content--);
}
var result = tmpArray.join();
...
Test out the code yourself, you'll find that the array method is much faster. If you are building up small strings in this manner, there's really not much difference between doing this in either manner since the total time spent doing this is small. But if you are going to be doing a larger operation, or the potential for a larger operation exists, you should make use of the more efficient method for building up strings in Javascript.
|

