achref achref - 13 days ago 6
Javascript Question

Is there a difference between concat(), "=" and "+="

I was wondering if there is any difference in performance between the following statements to concatinate two strings

str1='a'
and
str2='b'


str1 = str1 + str2;


or

str1 += str2;


or

var res = str1.concat(str2);


I have tried the following to measure the performance but the output seems to vary a lot from one execution to another for the same statement.

var str1='a', str2='b';
var old_time=new Date();
for (var i=0; i<=1000000 ; i++){
str1=str1+str2; // change this one with the other statements
}
var new_time=new Date();
console.log(new_time - old_time);

Answer

According to MDN: "It is strongly recommended that assignment operators (+, +=) are used instead of the concat() method. See this performance test."

Comments