如何确定节点.js的正确"max-old-space-size"?



我很难理解 Node.js 如何基于参数max-old-space-size进行操作。

例如,就我而言,我正在运行两个t2.smallAWS 实例(2GB RAM)。

不知道为什么,但我确实设置了max-old-space-size=4096(4GB)。在这种情况下,节点会做什么?此配置是否会导致可能的内存分配失败?

如何根据服务器资源确定正确的max-old-space-size值?

我的应用程序不断增加内存使用量,我正在尝试了解有关节点内部的所有内容。

"旧空间"是 V8 托管(也称为垃圾回收)堆(即 JavaScript 对象所在的位置)中最大和最可配置的部分,--max-old-space-size标志控制其最大大小。当内存消耗接近限制时,V8 将花费更多时间进行垃圾回收,以释放未使用的内存。

如果堆内存消耗(即 GC 无法释放的活动对象)超过限制,V8 将使进程崩溃(因为缺乏替代方案),因此您不想将其设置得太低。当然,如果你把它设置得太高,那么 V8 允许的额外堆使用可能会导致你的整个系统内存不足(并且由于缺乏替代方案,交换或杀死随机进程)。

总之,在具有 2GB 内存的机器上,我可能会将--max-old-space-size设置为 1.5GB 左右,以留出一些内存用于其他用途并避免交换。

2020 更新

这些选项现在由节点正式记录。对于 2GB 的计算机,您可能应该使用:

NODE_OPTIONS=--max-old-space-size=1536

确定要使用的量

您可以使用free -m查看 Linux 计算机上的可用内存。请注意,您可以将freebuffers/cache内存的总和视为可用,因为buffers/cache可以在需要时立即丢弃(这些缓冲区和缓存是使用其他未使用内存的好方法)。

max-old-space-size官方文档还提到:

在具有 2GB 内存的计算机上,请考虑将其设置为 1536 (1.5GB)

因此,上面的值。考虑到基本操作系统所需的内存量变化不大,因此您可以愉快地在 3.5GB 机器上执行 4GB 等。

要注意默认值并查看更改的效果,请执行以下操作:

默认值为 2GB:

$ node
> v8.getHeapStatistics()
{
....
heap_size_limit: 2197815296,
}

2197815296 是 2GB 的字节。

设置为 8GB 时,您可以看到heap_size_limit更改:

$ NODE_OPTIONS=--max_old_space_size=8192 node
Welcome to Node.js v14.17.4.
Type ".help" for more information.
> v8.getHeapStatistics()
{
...
heap_size_limit: 8640266240,
...
}

正如下面提到的@Venryx你也可以使用process.memoryUsage()

当为执行的应用程序分配的内存小于所需的内存时,会发生此错误。 默认情况下,Node.js 中的内存限制为 512 MB。要增加此数量,您需要将内存限制参数设置为—-max-old-space-size。这将有助于避免内存限制问题。

node --max-old-space-size=1024 index.js #increase to 1gb
node --max-old-space-size=2048 index.js #increase to 2gb
node --max-old-space-size=3072 index.js #increase to 3gb
node --max-old-space-size=4096 index.js #increase to 4gb
node --max-old-space-size=5120 index.js #increase to 5gb
node --max-old-space-size=6144 index.js #increase to 6gb
node --max-old-space-size=7168 index.js #increase to 7gb
node --max-old-space-size=8192 index.js #increase to 8gb

https://medium.com/@vuongtran/how-to-solve-process-out-of-memory-in-node-js-5f0de8f8464c

对我来说,当内存消耗接近 2GB 时,Azure 函数调用在 7GB 实例中终止,并显示以下错误消息。

Exception while executing function: Functions.graphql-mobile node exited with code 134
[24164:000001CE2EB5CF00] 10557962 ms: Scavenge (reduce) 2041.0 (2050.5) -> 2040.1 (2051.5) MB, 2.3 / 0.1 ms  (average mu = 0.179, current mu = 0.002) allocation failure ,FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory, 3: 00007FF73E006026 node::OnFatalError+294 

我通过在应用程序设置中像这样设置最大旧空间大小来解决此问题

"languageWorkers:node:arguments": "--max-old-space-size=5500"

最新更新