C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For concat, we call the method on a string. One or more arguments can be passed to concat().
JavaScript program that uses plus, concat on strings
var left = "cat and ";
var right = "bird";
// Use plus to concatenate strings.
var plusResult = left + right;
document.write(plusResult + "; ");
// Use concat method.
var concatResult = left.concat(right);
document.write(concatResult + "; ");
Output
cat and bird; cat and bird;
Concat: We can pass two strings as arguments to concat(). This is the same thing as using two plus signs to concatenate 3 strings.
JavaScript program that combines three 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.
document.write(all + "; ");
document.write(allConcat + "; ");
Output
abc; abc;
Program 1: This program uses string concat to create many large strings with a single character repeated in them.
Program 2: This program calls push() on an array to build up a buffer of 1 character repeated 10000 times.
Result: The array is faster. If an array can be used instead of concat(), this is likely a performance gain.
JavaScript program that benchmarks string concat
var x1 = performance.now();
// Append data to a string with concat.
for (var v = 0; v < 1000; v++) {
var letters = "";
for (var i = 0; i < 10000; i++) {
letters += "a";
}
}
var x2 = performance.now();
document.title = (x2 - x1);
JavaScript program that benchmarks array push
var x1 = performance.now();
// Append data to an array with push.
for (var v = 0; v < 1000; v++) {
var letters = [];
for (var i = 0; i < 10000; i++) {
letters.push("a");
}
}
var x2 = performance.now();
document.title = (x2 - x1);
Output
127.26 ms string concat
50.87 ms array push