37

Node.JS中用concat和push连接两个或多个数组的性能比较

 5 years ago
source link: http://ourjs.com/detail/5cb3fe1c44b4031138b4a1e2?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript中连接两个数组成一旧新数组,常用concat方法,比如:

var arr1 = [1,2,3,-1]
var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
var arr  = arr1.concat(arr2)

借用apply方法 ,push、splice也可和来连接数组。因为push没有创建新数组,如果想要保挂原对象的引用,可使用push方法。

那么两者在node.js的性能如何? 我们做了一组测试数据,两种分别测试100万次。

var testConcat = function(abc) {
  var arr1 = [1,2,3,-1]
  var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
  var arr  = arr1.concat(arr2)
}

var testPush = function(abc) {
  var arr1 = [1,2,3,-1]
  var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
  Array.prototype.push.apply(arr1, arr2)
}

var count = 1000000

var date = Date.now()
for (var i = 0; i < count; i++) {
    testConcat()
}
console.log(Date.now() - date)

var date = Date.now()
for (var i = 0; i < count; i++) {
    testPush()
}

console.log(Date.now() - date) 

结果:

$ node array.js
1470
465

由此可见,push比concat方法快3倍左右。因为push只是在原数组的基础上进行修改,所以会快一点。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK