-2

What will be the fastest and most appropriate way to concat or merge two strings. By using the '+' operator :

var str1 = "Hello ";
var str2 = "world!";
var res = str1 + str2;
// output : "Hello world!"

Or using the string concat :

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);
// output : "Hello world!"

The perspective is if the code has to be fast and optimized and production quality.And the above method will be used for constructing links,href and custom statements.. etc. Is there any other method to do so effeciently.

David H.
  • 953
  • 1
  • 8
  • 20
damitj07
  • 2,689
  • 1
  • 21
  • 40
  • 3
    This depends on the engine, but should be nearly equal. But if the string concatenation is a bottleneck in you code then you have another problem then using `+` or `concat` – t.niese Feb 25 '16 at 15:21
  • http://stackoverflow.com/questions/16124032/js-strings-vs-concat-method here you find the answer i think – Wouter den Ouden Feb 25 '16 at 15:21
  • 1
    http://www.sitepoint.com/javascript-fast-string-concatenation/ – Oscar LT Feb 25 '16 at 15:21
  • 2
    [Always read the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat#Performance). Also, [Which is faster?](http://ericlippert.com/2012/12/17/performance-rant/) – James Thorpe Feb 25 '16 at 15:21

2 Answers2

2

As it was already answered in SO using the + operator is more effective.

See MDN page about concat

It is strongly recommended that assignment operators (+, +=) are used instead of the concat() method.

Community
  • 1
  • 1
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
-2

Don't know if it's the fastest way, but what I find most readable (i.e. optimized for human eyes) is:

var str1 = "Hello ";
var str2 = "world!";
var res = [str1, str2].join('');
// output : "Hello world!"

Although usually only when we don't know ahead of time exactly what is going to be concatenated, so the sample looks really contrived.

Kris
  • 40,604
  • 9
  • 72
  • 101
  • 1
    Is it? Personally `+` is better for me. – Albzi Feb 25 '16 at 15:24
  • @Albzi it forces me to keep all the strings to be concatenated in one place (inside the array definition, so not littered throughout who knows where) and theoretically allows the runtime to know exactly how much memory is needed to store the end result so potentially less memory allocation. ymmv ofcourse. – Kris Feb 26 '16 at 09:44
  • @damitj07: it feels a bit weird that you would have selected this as your preferred answer, isn't Champagne's answer a better fit for you/your question? – Kris Feb 26 '16 at 09:47
  • Yes it would have been,but your answer sir , provides a new way and bit more customization ...as I may decide to concat with a special character in between. So that is what I thought. – damitj07 Feb 26 '16 at 09:53