js数组的性能问题

写个函数实现

输入[1,2,3]
返回[1,2,2,3,3,3]

当输入是[1,2,3,..10000]的时候,保证性能,
要怎么实现

深究 JavaScript 数组 —— 演进&性能
JavaScript 类型化数组

var arr = new Array(10000).fill(0).map((item,index) => index + 1)
function test(arr) {
    console.time('test');
    let res = []
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i]; j++) {
            res.push(arr[i])
        }
    }
    console.log(res.length);
    console.timeEnd('test');
    return res
}
test(arr)

var arr = new Array(10000).fill(0).map((item,index) => index + 1)
function test2(arr) {
    console.time('test2');
    let total = (1 + arr[arr.length - 1]) * arr.length / 2
    let buffer = new ArrayBuffer(total * 4)
    let typeArr = new Int32Array(buffer);
    let index = 0
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i]; j++) {
            typeArr[index++] = arr[i]
        }
    }
    console.log(typeArr.length);
    console.timeEnd('test2');
    return typeArr
}
test2(arr)
posted @ 2020-10-08 22:13  樱风凛  阅读(650)  评论(0编辑  收藏  举报