Array Join vs String Concat
Asked Answered
R

10

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];
}
Repellent answered 4/9, 2011 at 0:4 Comment(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 ).Do
What is the for loop for exactly? Just copying or are you doing processing in it. There are faster ways to copy an array.Metalwork
epascarello, they are just silly examples to test these 2 methodsRepellent
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.Sholes
It looks like currently in Chrome 53 and Firefox 48 the iteration faster then array join (link) more then 1,5 timeAriminum
U
51

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

http://jsben.ch/#/OJ3vo

Unmarked answered 4/9, 2011 at 0:10 Comment(15)
Safari seems to be the only browser where they're neck and neck.Unmarked
stitched 20 alphabets and it's the benchmark remains consistent.Unmarked
I also thought oppositely but I found another example jsperf.com/join-concat/2. Why is that? Isn't String immutable in ECMAScript?Shinto
We're not interacting with a String object here, just a string. See the difference: jsfiddle.net/AlienWebguy/92KTzUnmarked
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 iterationRepellent
String connect is 24% slower testing in Safari 7.0.4 on OS X 10.9.3 on my MBA.Adonic
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.Coakley
@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.Senaidasenalda
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.Senaidasenalda
This isn't true. I did some extensive tests under Node.js, and the results are quite the opposite. See github.com/nodejs/node/issues/6610Blur
I think there might be something wrong with the jsben.ch website. It's inconsistent with results from jsperf.com: #44612583Zone
2018, FF v59, result of mentioned link -> array join (fastest!)Catalpa
Both jsperf and jsben.ch give the same results for Chrome, concat is faster than arrays.Despairing
It sounds like browsers have evolved since 2011. That's insane.Unmarked
Join is faster in Firefox, Concat is faster in chrome (on Macbook Pro, circa 2015) , note also varargs vs code : jsben.ch/8xto9Failing
B
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.

Blur answered 6/5, 2016 at 2:37 Comment(1)
I came across this topic, and the other answers are maybe in 2011 correct, but at this moment the join is indeed better.Cirenaica
O
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.

Onstage answered 4/9, 2011 at 0:8 Comment(0)
L
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");

}
Leonardo answered 22/12, 2020 at 1:50 Comment(0)
M
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')
}
Myrmecophagous answered 4/6, 2021 at 15:46 Comment(4)
+1 for updated answer but really, I cringe when I look back 10 years and I were worried about performance, its all about code maintainanceRepellent
hi @Repellent , you shocked me as a beginner, I always thought that maintainance all about performance :)Shiva
It doesn't change much but your code also converts numbers to strings and this operation also takes some time.Malfeasance
@Malfeasance 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.Myrmecophagous
A
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

Autochthon answered 30/12, 2019 at 20:40 Comment(0)
B
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.

Barkentine answered 14/12, 2015 at 8:40 Comment(1)
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.Barth
M
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.

Myosotis answered 5/3, 2018 at 21:56 Comment(1)
Now with Chrome 65.0.3325.181, Array.join is 71% slower.Myosotis
W
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

Wilsonwilt answered 1/9, 2022 at 7:49 Comment(0)
H
-2

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

Hindustan answered 27/12, 2017 at 18:34 Comment(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.Savoie

© 2022 - 2024 — McMap. All rights reserved.