Reputation: 6018
I am trying to find a much better way to concatenate strings in javascript ES6. Below is the current code snippet.
Method 1:
function concat(...strings){
return ''.concat(...strings);
}
Method 2:
function concat(...strings){
return strings.join('');
}
Example:
concat("Hey", "There", "How", "Are", "You"); // output is "HeyThereHowAreYou"
I am not sure about the performance of these methods as the number of argument might increase. Any comment would be highly appreciated, which can be the best or any other approach can help.
Upvotes: 1
Views: 7359
Reputation: 380
ES5 Way: If you're not sure about nos argument passed then use arguments
object inside function.
function concat() {
let str = '';
for(let i=0; i < arguments.length; i++) {
str += arguments[i];
}
return str;
}
var resultant_str = concat("Hey", "There", "How", "Are", "You");
console.log(resultant_str);
ES6 Way: Use Rest params, it represents indefinite number of arguments as an Array.
function concat(... theArgs) {
return theArgs.reduce((prev, cur) => prev + cur);
}
var resultant_str = concat("Hey", "There", "How", "Are", "You");
console.log(resultant_str);
In terms of performance using for loop is much better because reduce requires a callback function which is called recursively. Abbreviated here.
Upvotes: 1
Reputation: 6819
I would suggest to go with using _.reduce. The reason being said it uses += kind of logic around arrays of string to concatenate and this is perf efficient jsperf
Snippet:
_.reduce(['x', 'y', 'z'], function(accumulator, currentItem) {
return accumulator + currentItem;
});
// xyz
Reference:
https://jsperf.com/concat-join-reduce
Upvotes: 2
Reputation: 603
String concatenation can be done in many ways
plus (+) operator. The + operator does string concatenation as soon as one of its operands is a string. Then the other operand is converted to a string. Example:
"Say hello " + 7 + " times fast!" ’Say hello 7 times fast!’
Alternatively, you can use += where
a += b
is an abbreviation for
a = a + b
Joining an array of strings. Collect the strings to be concatenated in an array and join it afterwards.
var arr = [];
arr.push("Say hello "); arr.push(7); arr.push(" times fast"); arr.join("") ’Say hello 7 times fast’
Which one is faster?
Strings being immutable, most string operations whose results are strings produce new strings.
Therefore languages such as C# or Java whose string handling is similar to JavaScript’s have special classes that help with concatenating strings. For example, C# calls this class StringBuilder. However, modern JavaScript engines optimize the + operator internally 1. Tom Schuster mentions Ropes 2 as one possible technique for optimization. Hence there is no need for StringBuilder in JavaScript.
Just use += and be done.
References:
“Re: String concatenation” – email by Brendan Eich stating that + is faster on modern JavaScript engines.
“Ropes: an Alternative to Strings (1995)” by Hans-J. Boehm , Russ Atkinson , Michael Plass.
Upvotes: 7