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];
}
Concatenation adds two strings and join separates the strings from Array. ' Join array.
Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.
String join is significantly faster then concatenation.
join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
String concatenation is faster in ECMAScript. Here's a benchmark I created to show you:
http://jsben.ch/#/OJ3vo
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With