Concat
Two strings (or more) can be combined into a single string
—this is called concatenation. In Node.js we use the plus operator or the concat method.
For performance, modern JavaScript runtimes handle concatenation in complex ways. They use "ropes" to avoid copying characters. There is no "string
builder" type in JavaScript.
Here we see 2 strings—left and right. We combine them with the plus operator and then we test the concat method. The syntax for concat()
is somewhat more complex.
string
. One or more arguments can be passed to concat()
.var left = "cat and "; var right = "bird"; // Use plus to concatenate strings. var plusResult = left + right; console.log(plusResult); // Use concat method. var concatResult = left.concat(right); console.log(concatResult);cat and bird cat and bird
The plus operator and the concat method can handle more than two strings at once. We can combine 3 or more strings—here we combine 3 strings.
concat()
. This is the same thing as using two plus signs to concatenate 3 strings.var one = "a"; var two = "b"; var three = "c"; // Concat 3 strings at once. var all = one + two + three; var allConcat = one.concat(two, three); // Write results. console.log(all); console.log(allConcat);abc abc
String
concatenation is fast in Node, but how does it compare to using an array? Here we compare similar programs that use concat and push.
string
concat to create many large strings with a single character repeated in them.push()
on an array to build up a buffer of 1 character repeated 10000 times.concat()
, this is likely a performance gain.// Version 1: append data to a string with concat. var x1 = performance.now(); for (var v = 0; v < 1000; v++) { var letters = ""; for (var i = 0; i < 10000; i++) { letters += "a"; } } // Version 2: append data to an array with push. var x2 = performance.now(); for (var v = 0; v < 1000; v++) { var letters = []; for (var i = 0; i < 10000; i++) { letters.push("a"); } } var x3 = performance.now(); console.log(x2 - x1); console.log(x3 - x2);45.46 ms string concat 38.73 ms array push
The plus sign and concat()
are equivalent in JavaScript engines. Internally a rope optimization is used to avoid copying—this makes many concatenations or appends faster.
String
concatenation is a common task in Node. With the powerful rope optimizations used, we can concatenate strings without too much performance loss.