Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Join vs String Concat

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];
}
like image 686
ajax333221 Avatar asked Sep 04 '11 00:09

ajax333221


People also ask

What is the difference between concat method and join method of array object?

Concatenation adds two strings and join separates the strings from Array. ' Join array.

Is concatenation faster than join?

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.

Is join faster than concatenation Python?

String join is significantly faster then concatenation.

What is array join?

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.


2 Answers

String concatenation is faster in ECMAScript. Here's a benchmark I created to show you:

http://jsben.ch/#/OJ3vo

like image 165
AlienWebguy Avatar answered Oct 12 '22 20:10

AlienWebguy


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.

like image 36
vitaly-t Avatar answered Oct 12 '22 18:10

vitaly-t