spread operator vs array.concat()

后端 未结 6 886
日久生厌
日久生厌 2020-12-01 04:00

What is the difference between spread operator and array.concat()

6条回答
  •  [愿得一人]
    2020-12-01 04:42

    I am replying just to the performance question since there are already good answers regarding the scenarios. I wrote a test and executed it on the most recent browsers. Below the results and the code.

    /*
     * Performance results.
     * Browser           Spread syntax      concat method
     * --------------------------------------------------
     * Chrome 75         626.43ms           235.13ms
     * Firefox 68        928.40ms           821.30ms
     * Safari 12         165.44ms           152.04ms
     * Edge 18           1784.72ms          703.41ms
     * Opera 62          590.10ms           213.45ms
     * --------------------------------------------------
    */
    

    Below the code I wrote and used.

    const array1 = [];
    const array2 = [];
    const mergeCount = 50;
    let spreadTime = 0;
    let concatTime = 0;
    
    // Used to popolate the arrays to merge with 10.000.000 elements.
    for (let i = 0; i < 10000000; ++i) {
        array1.push(i);
        array2.push(i);
    }
    
    // The spread syntax performance test.
    for (let i = 0; i < mergeCount; ++i) {
        const startTime = performance.now();
        const array3 = [ ...array1, ...array2 ];
    
        spreadTime += performance.now() - startTime;
    }
    
    // The concat performance test.
    for (let i = 0; i < mergeCount; ++i) {
        const startTime = performance.now();
        const array3 = array1.concat(array2);
    
        concatTime += performance.now() - startTime;
    }
    
    console.log(spreadTime / mergeCount);
    console.log(concatTime / mergeCount);
    

    I also wrote about the topic in my blog: https://www.malgol.com/how-to-merge-two-arrays-in-javascript/.

提交回复
热议问题