Javascript nodejs 内存不足
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7357339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs out of memory
提问by Sneaky Wombat
I came across a curious issue today. This may be an easy answer for others, but it has me stumped. Why does the code below cause a memory error?
我今天遇到了一个奇怪的问题。对于其他人来说,这可能是一个简单的答案,但它让我很难过。为什么下面的代码会导致内存错误?
var cur = 167772160;
var bcast = 184549375;
var addresses = [];
while (cur <= bcast){
cur += 1;
addresses.push(cur);
}
addresses.length
addresses // memory goes from a few megs to over a gig in seconds when trying to print this
I get one of these two errors...the first when i run this code in node's interpreter and the latter when i run it through nodeunit:
我得到了这两个错误之一……第一个是我在 node 的解释器中运行此代码时,后者是我通过 nodeunit 运行它时:
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
致命错误:CALL_AND_RETRY_2 分配失败 - 进程内存不足
FATAL ERROR: JS Allocation failed - process out of memory
致命错误:JS 分配失败 - 进程内存不足
采纳答案by ace
It happens when I try to access the array. But getting the length does not.
当我尝试访问数组时会发生这种情况。但得到长度没有。
> var cur = 167772160;
> var bcast = 184549375;
> var addresses = [];
> while (cur <= bcast){
... cur += 1;
... addresses.push(cur);
... }
16777216
> addresses.length
16777216
> addresses
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
Here's another SO question, memory limit in Node.js (and chrome V8)that relates to issue with memory usage.
这是另一个 SO 问题,Node.js(和 chrome V8)中的内存限制与内存使用问题有关。
回答by Saheed
You can increase the default limits by passing --max-old-space-size=<value>
which is in MB.
您可以通过传递--max-old-space-size=<value>
以 MB 为单位来增加默认限制。
The example will allow node's heap use up to 4GB (4096 megabytes) of memory:
该示例将允许节点的堆使用高达 4GB(4096兆字节)的内存:
node --max-old-space-size=4096 app
回答by Geuis
I don't get a memory allocation error when I run your script. How much RAM is on your system?
当我运行您的脚本时,我没有收到内存分配错误。你的系统有多少内存?
EditOk with the author's updated notes, I can replicate it.
用作者更新的笔记编辑好的,我可以复制它。
Node is trying to convert your entire array to a string. The array is 16777216 elements long. Each element contains a number at least 9 digits long. Converting that to a string 150,994,994 characters long. Its just a huge operation that is exceeding the memory capabilities of node.
Node 正在尝试将整个数组转换为字符串。该数组的长度为 16777216 个元素。每个元素包含一个长度至少为 9 位的数字。将其转换为长度为 150,994,994 个字符的字符串。它只是一个巨大的操作,超出了节点的内存容量。