前言
简单证明下不同数组拼接的效率问题,下面上结果(注意:我只在谷歌浏览器上进行了测试)
先说结论:arr.concat(array) > arr.push > arr[i] > [...arr] > arr.concat(i)
正文
<script>
// 测试数组拼接的效率问题
let n = 500000
function test1() {
let test_s = +new Date()
let arr = []
for (let i = 0; i < n; i++) {
arr[i] = i
}
let test_e = +new Date()
console.log('index:'+ (test_e - test_s) + 'ms lenth:' + arr.length)
}
function test2() {
let test_s = +new Date()
let arr = []
for (let i = 0; i < n; i++) {
arr.push(i)
}
let test_e = +new Date()
console.log('push:'+ (test_e - test_s) + 'ms lenth:' + arr.length)
}
let con_arr = []
for (let i = 0; i < n; i++) {
con_arr[i] = i
}
function test4() {
let test_s = +new Date()
let arr = []
arr = arr.concat(con_arr)
let test_e = +new Date()
console.log('concat(arr):'+ (test_e - test_s) + 'ms lenth:' + arr.length)
}
function test5() {
let test_s = +new Date()
let arr = []
arr = [...arr, ...con_arr]
let test_e = +new Date()
console.log('es6...:'+ (test_e - test_s) + 'ms lenth:' + arr.length)
}
test1()
test2()
test4()
test5()
</script>
下面是几组数据的测试结果