Which method is faster?
Array Join:
var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");
var output=myarray.join("");
String Concat:
var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");
var output = "";
for (var i = 0, len = myarray.length; i<len; i++){
output += myarray[i];
}
I can definitely say that using Array.join() is faster. I've worked on a few pieces of JavaScript code and sped up performance significantly by removing string manipulation in favor of arrays.
The spread operator, written with three consecutive dots ( ... ), is new in ES6 and gives you the ability to expand, or spread, iterable objects into multiple elements.
Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities
From 2011 and into the modern day ...
See the following
join
rewrite using string concatenation, and how much slower it is than the standard implementation.The moral is - do not concatenate strings manually, always use the standard
join
.Manual concatenation is faster, for a numeric array of fixed length.
Here's a JSPerf test that tests these two operations:
Results: Using Chrome 64.0.3282.186,
Array.join
was 46% slower.According to this Google document titled 'Optimizing JavaScript code' string concat is slower then array join but apparently this is not true for modern Javascript engines.
I made a benchmark for the Fibonacci test example that they used in the document and it shows that concatenating (gluing) the string is almost 4x as fast as using
Array
join
.String concatenation is faster in ECMAScript. Here's a benchmark I created to show you:
http://jsben.ch/#/OJ3vo