Array Join vs String Concat

前端 未结 7 967
一向
一向 2020-11-29 03:14

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         


        
相关标签:
7条回答
  • 2020-11-29 03:37

    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

    0 讨论(0)
  • 2020-11-29 03:39

    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.

    0 讨论(0)
  • 2020-11-29 03:40

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

    http://jsben.ch/#/OJ3vo

    0 讨论(0)
  • 2020-11-29 03:44

    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

    0 讨论(0)
  • 2020-11-29 03:57

    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.

    0 讨论(0)
  • 2020-11-29 04:02

    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.

    0 讨论(0)
提交回复
热议问题