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
It depends:
Array Join is 30% slower
String Concat is 90% slower
https://jsperf.com/lin-array-join-vs-string-concat
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.
// Number of times the standard `join` is faster, by Node.js versions:
// 0.10.44: ~2.0
// 0.11.16: ~4.6
// 0.12.13: ~4.7
// 4.4.4: ~4.66
// 5.11.0: ~4.75
// 6.1.0: Negative ~1.2 (something is wrong with 6.x at the moment)
function join(sep) {
var res = '';
if (this.length) {
res += this[0];
for (var i = 1; i < this.length; i++) {
res += sep + this[i];
}
}
return res;
}
The moral is - do not concatenate strings manually, always use the standard join
.
String concatenation is faster in ECMAScript. Here's a benchmark I created to show you:
http://jsben.ch/#/OJ3vo
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.
const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);
Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities
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
.
Manual concatenation is faster, for a numeric array of fixed length.
Here's a JSPerf test that tests these two operations:
zxy.join('/')
// versus
zxy[0] + '/' + zxy[1] + '/' + zxy[2]
// given the array
zxy = [1, 2, 3]
// resulting in the string '0/1/2'
Results: Using Chrome 64.0.3282.186, Array.join
was 46% slower.