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>

3
  • 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 ! Commented Dec 25, 2015 at 19:53
  • 2
    See ES5 §15.5.4.6 concat and compare against §11.6.1 addition operator; 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 Commented Dec 25, 2015 at 20:04
  • @PeeHaa Oops, sorry about that. Commented Dec 26, 2015 at 4:21

3 Answers 3

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>");
}

Sign up to request clarification or add additional context in comments.

8 Comments

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.
@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.
@LeventDivilioglu - Added performance data and graph to my answer.
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?
@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.
|
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.

1 Comment

The performance test is a broken link. I'm seeing this response, {"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}
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

6 Comments

I didn't, I've already gave an upvote for your statement about the + operators performance superiority because it was useful.
It's requested to every guy to please comment for downvote reason, so that i can learn my mistake. And @LeventDivilioglu thanks
Did not downvote, but a link or some citation to the claim would be good.
@xbonez, I'll take care for that .Thanks for your valuable suggestion.
This answer seems like just a comment as there is no explanation or reference given.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.