80

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];
}
philipxy
  • 14,867
  • 6
  • 39
  • 83
ajax333221
  • 11,436
  • 16
  • 61
  • 95
  • Depends what you want. The String method is slightly simpler. The Array join way might be a bit faster (you could test on jsperf.com ). – andrewmu Sep 04 '11 at 00:08
  • What is the for loop for exactly? Just copying or are you doing processing in it. There are faster ways to copy an array. – epascarello Sep 04 '11 at 00:17
  • epascarello, they are just silly examples to test these 2 methods – ajax333221 Sep 04 '11 at 00:39
  • 1
    I remember reading some articles a couple of years ago quoting performance stats to prove that the array method is faster than string concatenation, but even back then it varied from browser to browser. Seems to me that these types of performance things reverse every time the next generation of browsers comes out. – nnnnnn Sep 04 '11 at 06:18
  • It looks like currently in Chrome 53 and Firefox 48 the iteration faster then array join ([link](http://perfjs.info/#!/F33A9807-6D63-4773-AF70-7DA57E79A90C)) more then 1,5 time – Pencroff Sep 18 '16 at 15:06

10 Answers10

50

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

http://jsben.ch/#/OJ3vo

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Safari seems to be the only browser where they're neck and neck. – AlienWebguy Sep 04 '11 at 00:15
  • stitched 20 alphabets and it's the benchmark remains consistent. – AlienWebguy Sep 04 '11 at 00:25
  • I also thought oppositely but I found another example http://jsperf.com/join-concat/2. Why is that? Isn't String immutable in ECMAScript? – Sanghyun Lee Sep 04 '11 at 00:38
  • We're not interacting with a String object here, just a string. See the difference: http://jsfiddle.net/AlienWebguy/92KTz/ – AlienWebguy Sep 04 '11 at 00:49
  • 1
    Update: there are some important things I found, 1) we are unnecessarily recreating the array in the join example, 2) it would be better if we stored the array length to prevent checking the length on every iteration – ajax333221 Dec 11 '12 at 02:42
  • String connect is 24% slower testing in Safari 7.0.4 on OS X 10.9.3 on my MBA. – Matt Jun 23 '14 at 20:02
  • Another important factor is the **length** of each string piece to stitch together and their **amount**. If you deal with only a few and small character strings, the above tests show that string concatenation is more efficient. But if you deal with larger strings or huge amounts of them, ajax333221's fixed JSPerf shows that joining an array of those strings is faster. – David Bonnet Aug 26 '14 at 10:39
  • 10
    @ajax333221: *"We are unnecessarily recreating the array in the join example"* Creating the array in order to join it **is the whole point**. Your updated jsperf compares apples with oranges. If you *already* have an array, yes, `join` is faster. But what people are comparing is *creating* an array just to join it, vs. doing string concat. Different kettle of fish entirely. – T.J. Crowder Sep 15 '15 at 08:45
  • 4
    Apples to apples: Joining strings of varying lengths 2000 times, either building up in an array and doing `join`, or using string concat. http://jsperf.com/yet-another-array-vs-concat Concat wins with modern engines for performance, and of course has always won for readability/maintainability/debugability. When I tried this 10 years ago, performance was slightly better with arrays. Not so anymore. – T.J. Crowder Sep 15 '15 at 08:58
  • This isn't true. I did some extensive tests under Node.js, and the results are quite the opposite. See https://github.com/nodejs/node/issues/6610 – vitaly-t May 06 '16 at 02:32
  • 1
    I think there might be something wrong with the jsben.ch website. It's inconsistent with results from jsperf.com: https://stackoverflow.com/questions/44612083/which-js-benchmark-site-is-correct – Venryx Jun 18 '17 at 05:45
  • 1
    2018, FF v59, result of mentioned link -> `array join (fastest!)` – Mehdi Dehghani Mar 18 '18 at 07:58
  • Both jsperf and jsben.ch give the same results for Chrome, concat is faster than arrays. – mbomb007 Apr 19 '18 at 15:51
  • It sounds like browsers have evolved since 2011. That's insane. – AlienWebguy Apr 20 '18 at 20:26
  • Join is faster in Firefox, Concat is faster in chrome (on Macbook Pro, circa 2015) , note also varargs vs code : http://jsben.ch/8xto9 – Charles Hebdough Apr 30 '19 at 16:56
10

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.

Melchia
  • 22,578
  • 22
  • 103
  • 117
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • 6
    I came across this topic, and the other answers are maybe in 2011 correct, but at this moment the join is indeed better. – Cageman May 30 '17 at 09:00
9

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.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63
7

join is way faster when the array of strings already exists. The real comparison would be comparing:

  1. push elements into the array and then join them to build the string
  2. concatenate string every time without using the array

For small number of iteration and strings, it does not matter whether you use push-and-join or concatenate. However, for large number of strings, array push and join seems to be faster in both chrome and firefox.

Here is the code and the test results for 10 to 10 million strings:

Chrome:

strings 10
join-only: 0.01171875 ms
push-join: 0.137939453125 ms
concatenate: 0.01513671875 ms
strings 100
join-only: 0.01416015625 ms
push-join: 0.13427734375 ms
concatenate: 0.0830078125 ms
strings 1000
join-only: 0.048095703125 ms
push-join: 0.47216796875 ms
concatenate: 0.5517578125 ms
strings 10000
join-only: 0.465087890625 ms
push-join: 5.47314453125 ms
concatenate: 4.9619140625 ms
strings 100000
join-only: 7.6240234375 ms
push-join: 57.37109375 ms
concatenate: 67.028076171875 ms
strings 1000000
join-only: 67.666259765625 ms
push-join: 319.3837890625 ms
concatenate: 609.8369140625 ms
strings 10000000
join-only: 824.260009765625 ms
push-join: 3207.129150390625 ms
concatenate: 5959.56689453125 ms

Firefox:

strings 10
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 100
join-only: 0ms
push-join: 0ms
concatenate: 0ms
strings 1000
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 10000
join-only: 1ms
push-join: 2ms
concatenate: 0ms
strings 100000
join-only: 5ms
push-join: 11ms
concatenate: 8ms
strings 1000000
join-only: 39ms
push-join: 88ms
concatenate: 98ms
strings 10000000
join-only: 612ms
push-join: 1095ms
concatenate: 3249ms

Code to test:

for (var n = 10; n <= 10000000; n*=10) {
    
    var iterations = n;

    console.log("strings", iterations);
    console.time("push-join");
    arr = [];
    for (var i = 0; i< iterations; i++) {
        arr.push("a b c d e f g h i j k l m");
    }
    console.time("join-only");
    content = arr.join(",");
    console.timeEnd("join-only");
    console.timeEnd("push-join");

    content = "";

    console.time("concatenate");    
    for (var i = 0; i< iterations; i++) {
        content += "a b c d e f g h i j k l m";
    }
    console.timeEnd("concatenate");

}
Yves M.
  • 29,855
  • 23
  • 108
  • 144
K Vij
  • 1,783
  • 1
  • 12
  • 19
5

2021 test

See code below. Results:

Firefox: push+join is 80% slower than string concat, in regular usage.

Chrome: push+join is 140% slower than string concat, in regular usage.

function test(items = 100, rep = 1000000) {
  let str

  console.time('concat')
  for (let r = 0; r < rep; r++) {
    str = ''
    for (let i = 0; i < items; i++) {
      str += i
    }
  }
  console.timeEnd('concat')

  console.time('push+join')
  for (let r = 0; r < rep; r++) {
    const arr = []
    for (let i = 0; i < items; i++) {
      arr.push(i)
    }
    str = arr.join('')
  }
  console.timeEnd('push+join')
}
Tobia
  • 17,856
  • 6
  • 74
  • 93
  • 2
    +1 for updated answer but really, I cringe when I look back 10 years and I were worried about performance, its all about code maintainance – ajax333221 Jun 04 '21 at 21:59
  • hi @ajax333221 , you shocked me as a beginner, I always thought that maintainance all about performance :) – Ayman Morsy Feb 02 '22 at 20:04
  • It doesn't change much but your code also converts numbers to strings and this operation also takes some time. – NtsDK Jul 12 '23 at 10:42
  • @NtsDK I guess so, but each integer should be converted the same number of times in both cases, so it's a constant offset. If anything, it would make the speed ratios even more extreme. – Tobia Jul 13 '23 at 11:09
4

It depends:

Chromium 79.0.3945

Array Join is 30% slower

Firefox 71.0.0

String Concat is 90% slower

https://jsperf.com/lin-array-join-vs-string-concat

Lin
  • 1,041
  • 10
  • 6
2

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.

Melchia
  • 22,578
  • 22
  • 103
  • 117
Wilt
  • 41,477
  • 12
  • 152
  • 203
  • 2
    The benchmark is not very good as you don't only compare string concatenation with joining an array but in the join-case create a new array in the benchmark as well. – dpr Aug 21 '17 at 15:52
1

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.

Matthias
  • 13,607
  • 9
  • 44
  • 60
1

i think it is not only performance problem, but memory too

as string is immutable, means every time you concat a string, a extra string create in your memory

but array is mutable, mean it will keep the same memory address

of course it is also depend on languages, in general , array is a better solution

user192344
  • 1,274
  • 6
  • 22
  • 36
-1

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

Melchia
  • 22,578
  • 22
  • 103
  • 117
  • 1
    This only works if your function accepts multiple (`...rest`) arguments. `console.log` is such an example. However, this does not always answer OP’s question because you may be using a function that only accepts 1 string parameter, in which case the spread operator would fail. – chharvey Jan 23 '18 at 23:07