83

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];
}
5
  • 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
    Commented Sep 4, 2011 at 0: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. Commented Sep 4, 2011 at 0:17
  • epascarello, they are just silly examples to test these 2 methods
    – ajax333221
    Commented Sep 4, 2011 at 0: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
    Commented Sep 4, 2011 at 6:18
  • It looks like currently in Chrome 53 and Firefox 48 the iteration faster then array join (link) more then 1,5 time
    – Pencroff
    Commented Sep 18, 2016 at 15:06

10 Answers 10

51

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

http://jsben.ch/#/OJ3vo

15
  • 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
    Commented Dec 11, 2012 at 2:42
  • 12
    @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. Commented Sep 15, 2015 at 8: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. 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. Commented Sep 15, 2015 at 8:58
  • 1
    I think there might be something wrong with the jsben.ch website. It's inconsistent with results from jsperf.com: stackoverflow.com/questions/44612083/…
    – Venryx
    Commented Jun 18, 2017 at 5:45
  • 1
    2018, FF v59, result of mentioned link -> array join (fastest!) Commented Mar 18, 2018 at 7:58
11

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.

1
  • 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
    Commented May 30, 2017 at 9: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.

0
7

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')
}
4
  • 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
    Commented Jun 4, 2021 at 21:59
  • hi @ajax333221 , you shocked me as a beginner, I always thought that maintainance all about performance :) Commented Feb 2, 2022 at 20:04
  • It doesn't change much but your code also converts numbers to strings and this operation also takes some time.
    – NtsDK
    Commented Jul 12, 2023 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
    Commented Jul 13, 2023 at 11:09
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");

}
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

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.

1
  • 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
    Commented Aug 21, 2017 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.

1
  • Now with Chrome 65.0.3325.181, Array.join is 71% slower.
    – Matthias
    Commented Apr 10, 2018 at 16:42
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

-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

1
  • 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
    Commented Jan 23, 2018 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.