JS數組:push vs concat

使用JS這麼久, 對於JS數組的相關方法一直都是拿來就用,對於push方法更是經常使用。可是在一次用到contact方法的時候自問了一句: pushcontact到底有哪些區別?chrome

先看下MDN的定義:數組

push:adds one or more elements to the end of an array and returns the new length of the array.
var animals = ['pigs', 'goats', 'sheep'];
console.log(animals.push('cows')); // expected output: 4
console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"]


animals.push(['new arr']); // expected output: 5
console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", Array(1)]
contact:The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2)); // expected output: Array ["a", "b", "c", "d", "e", "f"]
console.log(array1); // expected output: Array ["a", "b", "c"]
console.log(array2); // expected output: Array ["d", "e", "f"]

摘取重點:性能

  1. push方法添加元素到數組末尾,改變的是同一個數組, 返回值是添加以後數組的長度
  2. contact方法是合併兩個或者多個數組,不會改變存在的數組,返回的是合併的數組

那性能會不會有區別?code

環境:win8.1 chrome 63.0.3239.132ip

// push demo
var arr3 = [1, 2, 3];
var arr4 = [4, 5, 6];
console.time('push');
for (let index = 10000; index > 0; index--) {
  arr3.push(...arr4);
}
console.timeEnd('push'); // push: 2.39892578125ms
// contact demo
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.time('contact');
for (let index = 10000; index > 0; index--) {
  arr1 = arr1.concat(arr2);
}
console.timeEnd('contact'); // contact: 312.762939453125ms

在我這個環境上push+解構的性能是要好於contact的。不過對於多個數組合並的時候, contact由於返回的是新數組,能夠鏈式下去。element

相關文章
相關標籤/搜索