19

The plus ( + ) operator and String.concat() method gives the same result.

plus ( + ) operator;

str1 + str2;

String concat() method;

str1.concat(str2);

Addionally, it is written in w3schools ;

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

So which way is better to use to combine for either we use on primitives or on String objects in JS, what are the performance advantages and disadvantages between them if there is any?

var firstName = "John"      // String
var y = new String("John"); // with String Object

Here are the example codes which give same results;

function example1 () {
  var str1 = "Hello ";
  var str2 = "World!";
  document.getElementById("demo1").innerHTML += str1 + str2;
}


function example2 () {
  var str1 = "Hello ";
  var str2 = "World!";
  document.getElementById("demo2").innerHTML += str1.concat(str2);
}

function example3 () {
  var str1 = String("Hello ");
  var str2 = String("World!");
  document.getElementById("demo3").innerHTML += str1 + str2;
}

function example4 () {
  var str1 = String("Hello ");
  var str2 = String("World!");
  document.getElementById("demo4").innerHTML += str1.concat(str2);
}

example1();
example2();
example3();
example4();
<p id="demo1">Demo 1: </p>
<p id="demo2">Demo 2: </p>
<p id="demo3">Demo 3: </p>
<p id="demo4">Demo 4: </p>
Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106
  • This question is about javascript, not java! and secondly, it is not only about operator vs. concat() but also the behaviour about the primitives and objects in javascript. The referenced question is not the duplicate of this. Should be reopened ! – Levent Divilioglu Dec 25 '15 at 19:53
  • 2
    See ES5 [**§15.5.4.6** concat](http://es5.github.io/#x15.5.4.6) and compare against [**§11.6.1** addition operator](http://es5.github.io/#x11.6.1); Primary difference is you can call `.concat` on _non-Strings_ and assume the result is a _String_ `String.prototype.concat.call(1, 2); // "12"` vs `1 + 2; // 3` – Paul S. Dec 25 '15 at 20:04
  • @PeeHaa Oops, sorry about that. –  Dec 26 '15 at 04:21

3 Answers3

14

There is no difference in behavior between the string methods on a primitive and the string methods on an object.

There is a big difference in performance as the primitive versions appear to be much faster in this jsperf (perhaps as much as 100x faster), likely due to interpreter optimizations.

enter image description here

As you can see from this jsperf, the main difference in performance is caused by var str1 = new String("Hello "); instead of var str1 = "Hello ";. The + operator vs. concat() does not make much difference at all. My guess is this is because the JS interpreter is optimizing the string method. But, creating an actual string object isn't as optimized or efficient.

As for the ECMAScript specification, in the ECMAScript spec for +, it explicitly says that if the primitive value of the left operand (lprim) is a string, then return the string that is the result of concatenating ToString(lprim) followed by ToString(rprim).

In the ECMAScript spec for String.prototype.concat(), it says: Let R be the String value consisting of the characters in the previous value of R followed by the characters of ToString(next).

This wording implies that + when given a left operand as a string is going to cast the right operand to a string and call .concat() internally which is exactly what .concat() does.

Obviously if the left operand is not a string, then you would get a different behavior with + as it won't necessarily treat it as a string operation at all.


A situation that it can make a difference whether you have a string object or a string primitive is if you want to add a custom property to a string object, then you need the object form, not the primitive form.

As for when to use + and when to use .concat(), this is a personal coding style choice. Both achieve the same results. I personally prefer using operators when possible as the code just seems simpler to read.

Unless you have a specific reason to make a string object, then you should generally just use primitives.

So, there's really no reason to do this:

var str1 = String("Hello ");
var str2 = String("World!");
document.getElementById("demo").innerHTML = str1.concat(str2);

when this works just fine:

var str1 = "Hello ";
var str2 = "World!";
document.getElementById("demo").innerHTML = str1 + str2;

Here's an example of the only time I know of when you might want/need an explicit string object:

// actual string object will retain custom property
var str1 = new String("Hello");
str1.customProp = "foo";
log(str1.customProp);

// string primitive will not retain custom property
var str2 = "Hello";
str2.customProp = "foo";
log(str2.customProp);

function log(x) {
    document.write(x + "<br>");
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • So is it valid to say that String.concat() and '+' operator is totally equal and identical, is it valid to say that they are processed in the same way with the same performance behind the scenes on both primitives and objects in JavaScript ? I'm still curious. – Levent Divilioglu Dec 25 '15 at 20:00
  • @LeventDivilioglu - `+` and `.concat()` provide exactly the same result. As for performance questions, you'd have to run some performance measuring tests in multiple browsers to answer that as that could be implementation dependent. There is no conceptual reason why one must be faster or slower than the other. – jfriend00 Dec 25 '15 at 20:02
  • 1
    @LeventDivilioglu - Added performance data and graph to my answer. – jfriend00 Dec 25 '15 at 20:22
  • Any particular reason why you are using `String` for one and not the other? Shouldn't both tests work with quoted strings or the objects? – Kevin Brown-Silva Dec 26 '15 at 01:52
  • @KevinBrown - I just picked the OP's example1 and example4 to compare since the OP seemed to be asking about both String objects vs. primitives and methods vs. operators. – jfriend00 Dec 26 '15 at 02:49
  • @jfriend00 The "big difference" appears to largely be a result of the `String` vs primitive difference. [See this updated jsPerf test.](http://jsperf.com/string-object-vs-primitive/2) – Kevin Brown-Silva Dec 27 '15 at 22:34
  • @KevinBrown - agreed. The main difference appears to be the declaration. – jfriend00 Dec 27 '15 at 23:48
  • @KevinBrown - I incorporated your jsperf and the info it shows into my answer. – jfriend00 Dec 28 '15 at 01:07
6

There are pretty the same but + is more clear and for sure faster.

Look at this performance test and also see this

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

Robert
  • 19,800
  • 5
  • 55
  • 85
  • 1
    The performance test is a broken link. I'm seeing this response, `{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}` – Rod Talingting Jul 07 '20 at 14:17
1

No difference according to functionality but '+' operator is faster that concat() for performance.

var str1="hello";
var str2="world";
var str3;
var start = new Date().getTime();
for (i = 0; i < 100000; ++i) {
str3=str1+str2;
}
var end = new Date().getTime();
var time = end - start;

print('Execution time using + operator: ' + time);

// USING CONCAT OPERATOR

start = new Date().getTime();
for (i = 0; i < 100000; ++i) {
str3=str1.concat(str2);
}
end = new Date().getTime();
time = end - start;
print('Execution time using CONCAT operator: ' + time);

please run at ideone

Ambika
  • 594
  • 2
  • 11
  • I didn't, I've already gave an upvote for your statement about the + operators performance superiority because it was useful. – Levent Divilioglu Dec 25 '15 at 19:49
  • It's requested to every guy to please comment for downvote reason, so that i can learn my mistake. And @LeventDivilioglu thanks – Ambika Dec 25 '15 at 19:54
  • 1
    Did not downvote, but a link or some citation to the claim would be good. – Ayush Dec 25 '15 at 20:00
  • @xbonez, I'll take care for that .Thanks for your valuable suggestion. – Ambika Dec 25 '15 at 20:02
  • 1
    This answer seems like just a comment as there is no explanation or reference given. – jfriend00 Dec 25 '15 at 20:13
  • 1) Starting an answer by mentioning a user immediately makes it look like your answer is a comment. In this case, the person you mention is the asker of the question (who gets a notification for every answer) so the mention is not necessary. 2) As @jfriend00 points out, your answer has no explanation or reference. 3) I'm not a downvoter in this case, but have edited out the mention. – Wai Ha Lee Dec 25 '15 at 20:19