Joining Strings Together

by jeremyjones on March 19, 2011

  • Share
  • CevherShare
  • Share

It is common to wish to join several smaller strings together into a large string. The obvious way to do this is with a string concatenation operation, but in JavaScript this can have a bad affect on performance. This is because the string concatenation operations can produce too many intermediate strings, which will make it perform poorly. This example demonstrates string concatenation:

<script>// <![CDATA[
>var str1, str2, strConcat;
str1 = "Concatenating "; // String 1
str2 = "strings"; // String 2
strConcatd = str1 + str2; // Join them together
document.write (strConcat); // Print the result
// ]]></script>

As the number of concatenation operations increases, it can be better to use another concatenation method like the Array.join() function which joins the strings together into an array. This example shows how to use Array.join():

<script>// <![CDATA[
Var temp = [];
For (/* every bit*/)
{
	Temp.push(bit);
}
Str1 = tmp.join(‘’)
Document.write (str1);
// ]]></script>

An alternative method is to use the string.concat() method to join the strings together. This example demonstrates the use of this method:

<script type="”text/javascript">// <![CDATA[
Var str1=”Hello ”;
Var str2 = “world!;
Document.write(str1.concat(str2));
// ]]></script>

Different browsers support all three of these methods, but the browser performance can differ between browsers and even versions of the same browser. To optimize your code, write a sample of code that uses each method a lot of times (one million for example), time the results with different browsers, and see which is consistently the fastest. Use the fastest for your string operations for optimum results.

Leave a Comment

Previous post:

Next post: