High-performance String Concatenation in JavaScript

Share this article

Concatenation, or joining strings, is an important facility within any programming language. It’s especially vital within web applications, since strings are regularly used to generate HTML output. Several languages offer fast string-handling classes such as StringBuilder in .NET and StringBuffer/StringBuilder in Java. There are a number of ways to concatenate strings in JavaScript:


str = "a" + "b";
str += "c";
str = str.concat("d", "e");
You can also join an array of strings:

str = ["a", "b", "c", "d", "e"].join("");
If you’re only joining a few strings, you should use whichever method is most practical. Performance gains or losses will be negligible in all browsers.

Concatenating Many Strings

Consider the following functionally identical examples. The first uses the string concatenation operator:

// standard string append
var str = "";
for (var i = 30000; i > 0; i--) {
	str += "String concatenation. ";
}
The second uses an array join:

// array join
var str = "", sArr = [];
for (var i = 30000; i > 0; i--) {
	sArr[i] = "String concatenation. ";
}
str = sArr.join("");
Which will execute the fastest? Some developers will assume the concatenation operator is faster because it uses less code and doesn’t require an array that doubles memory requirements. For others, conventional wisdom dictates that array joins are faster—it’s more memory efficient within the JavaScript interpreter. The truth is rather more complex. In all the most recent browsers, either method is fast and will complete within 80ms on a mid-range PC. Here are the results from my own completely unscientific benchmark tests:
  • Chrome 6.0: standard string appends are usually quicker than array joins, but both complete in less than 10ms.
  • Opera 10.6: again, standard appends are quicker, but the difference is marginal—often 15ms compared to 17ms for an array join.
  • Firefox 3.6: the browser normally takes around 30ms for either method. Array joins usually have the edge, but only by a few milliseconds.
  • IE 8.0: a standard append requires 30ms, whereas an array join is more than double—typically 70ms.
  • Safari 5.0.1: bizarrely, a standard append takes no more than 5ms but an array join is more than ten times slower at 55ms.
The latest JavaScript engines are optimized for string concatenation operators. Array joins remain fast, but are without a performance gain.

The flIEs in the ointment

IE7 is the world’s third-most-used browser with a 14% market share. IE6 accounts for another 8%. There’s no need to read further if you’ve dropped support for these aging applications. Still here? This is the shocker: IE7 and below use a concatenation handler that repeatedly copies strings and causes an exponential increase in time and memory usage. The code using the concatenation operator takes around 2.5 minutes (150,000ms) to execute, and the browser remains unresponsive throughout. By comparison, the array join completes in under 200ms—it’s more than 800 times faster. If you’re supporting IE7, array joins remain the best method for concatenating a large number of strings. What about PHP? Tune in soon for the test results…

Frequently Asked Questions about JavaScript String Concatenation

Why is string concatenation in JavaScript important?

String concatenation is a fundamental concept in JavaScript, and it’s used to combine two or more strings. It’s important because it allows developers to create dynamic strings, which are essential for creating interactive web pages. For example, you might use string concatenation to create a personalized greeting for a user based on their name, or to build a URL for an API request based on user input.

What is the difference between using “+” and “concat()” for string concatenation in JavaScript?

Both “+” and “concat()” can be used for string concatenation in JavaScript, but there are some differences. The “+” operator is more straightforward and easier to read, but it can lead to confusion if you’re trying to add a number to a string, as JavaScript will try to convert the string to a number. On the other hand, the “concat()” method is more explicit and can concatenate multiple strings at once, but it’s slightly slower and less commonly used.

How can I improve the performance of string concatenation in JavaScript?

There are several ways to improve the performance of string concatenation in JavaScript. One method is to use the “+=” operator instead of the “+” operator, as it’s faster and more efficient. Another method is to use an array and the “join()” method, which can be faster for large amounts of data. However, the best method depends on your specific use case and the size of the data you’re working with.

Does JavaScript have a built-in StringBuilder class like Java?

No, JavaScript does not have a built-in StringBuilder class like Java. However, you can achieve similar functionality using an array and the “join()” method. This method is particularly efficient for large amounts of data, as it avoids creating unnecessary intermediate strings.

What are the best practices for string concatenation in JavaScript?

The best practices for string concatenation in JavaScript depend on your specific use case. However, some general tips include using the “+=” operator for small amounts of data, using an array and the “join()” method for large amounts of data, and avoiding the “concat()” method unless you need to concatenate multiple strings at once. It’s also important to be aware of the potential for type coercion when using the “+” operator.

Can I use template literals for string concatenation in JavaScript?

Yes, you can use template literals for string concatenation in JavaScript. Template literals are a feature of ES6, and they allow you to embed expressions within string literals. They’re particularly useful for creating complex strings, as they allow you to include variables, expressions, and even function calls directly within the string.

How does string concatenation work in JavaScript compared to other languages?

String concatenation in JavaScript is similar to many other languages, but there are some differences. For example, JavaScript uses the “+” operator for string concatenation, while some other languages use the “&” operator. Additionally, JavaScript does not have a built-in StringBuilder class like Java, but you can achieve similar functionality using an array and the “join()” method.

What are the potential pitfalls of string concatenation in JavaScript?

One potential pitfall of string concatenation in JavaScript is type coercion. If you try to add a number to a string using the “+” operator, JavaScript will try to convert the string to a number, which can lead to unexpected results. Another potential pitfall is performance. String concatenation can be slow for large amounts of data, so it’s important to use efficient methods like the “+=” operator or the “join()” method.

How can I concatenate strings with special characters in JavaScript?

You can concatenate strings with special characters in JavaScript using the “+” operator or the “concat()” method. If the special character is part of the string, you can include it directly within the string literal. If the special character is a variable or expression, you can include it within the string using template literals.

Can I concatenate strings with other data types in JavaScript?

Yes, you can concatenate strings with other data types in JavaScript. However, be aware that JavaScript will try to convert the other data type to a string. For example, if you try to concatenate a string with a number, JavaScript will convert the number to a string. If you try to concatenate a string with an object, JavaScript will convert the object to the string “[object Object]”.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

concatenationjavascriptstrings
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week