gpt4 book ai didi

javascript - 数组(大小)。填充(1): 500x more time and 70x more memory with 10x more data

转载 作者:行者123 更新时间:2023-12-04 13:25:54 25 4
gpt4 key购买 nike

我正在对一些简单的 javascript 代码进行基准测试,并且在以下示例中看到了一些意外的内存使用情况:

function startTimer() {
const time = process.hrtime();
return time;
}

function endTimer(time) {
function roundTo(decimalPlaces, numberToRound) {
return +(Math.round(numberToRound + `e+${decimalPlaces}`) + `e-${decimalPlaces}`);
}
const diff = process.hrtime(time);
const NS_PER_SEC = 1e9;
const result = (diff[0] * NS_PER_SEC + diff[1]); // Result in Nanoseconds
const elapsed = result * 0.0000010;
return roundTo(6, elapsed); // Result in milliseconds
}

SIZE = 10000000

start = startTimer()
let a = Array(SIZE).fill(1)
elapsed = endTimer(start)

const proc = process.memoryUsage()
console.log("rss (MB): ", proc.rss/1000/1000)
console.log("heapTotal (MB): ", proc.heapTotal/1000/1000)
console.log("heapUsed (MB): ", proc.heapUsed/1000/1000)
console.log("elapsed (ms): ", elapsed)
当 SIZE = 10MB 时,我得到:
[ThinkPad-E14-Gen-2:/home/jj/Documents/repos/tests_javascript]% node --max-old-space-size=4192  example.js
SIZE (MB): 10
rss (MB): 113.87
heapTotal (MB): 84.19
heapUsed (MB): 83.29
elapsed (ms): 47.44
当 SIZE = 100MB 时,我的 RSS 内存增加了 66 倍,执行时间增加了 500 倍:
[ThinkPad-E14-Gen-2:/home/jj/Documents/repos/tests_javascript]% node --max-old-space-size=4192  example.js
SIZE (MB): 100
rss (MB): 7529.71
heapTotal (MB): 4083.26
heapUsed (MB): 4008.59
elapsed (ms): 23135.14
为什么会这样?我如何进行时间/内存分配的基准测试?

最佳答案

您可能会发现这很有用:

  • https://v8.dev/blog/elements-kinds
  • https://bugs.chromium.org/p/v8/issues/detail?id=6892
  • https://2ality.com/2018/12/creating-arrays.html

  • 性能损失可能是由于 Array(SIZE) 产生的多孔阵列类型所致。构造函数。
    看完上面的文章,你可能会发现比较填充 10_000_00在内存和时间上的差异很有趣。和(说) 50_000_000用这种方式数组:
    let a = Array(SIZE).fill(1)

    let a = Array.from({ length: SIZE }).fill(1)

    let a = [1]; for (let i = 0; i < SIZE; i++) a.push(1);

    let a = [1]; for (let i = 0; i < SIZE; i++) a[i] = 1;

    let a = new Uint8Array(SIZE).fill(1) // Wow!

    关于javascript - 数组(大小)。填充(1): 500x more time and 70x more memory with 10x more data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68516200/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com