NodeJS在无限循环中的内存消耗 [英] NodeJS memory consumption in an infinite loop

查看:882
本文介绍了NodeJS在无限循环中的内存消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是Node或V8的错误,但如果我运行以下代码,则节点进程会泄漏内存。 GC似乎永远不会启动,并且在几秒钟内消耗了大约1GB的内存。这是出乎意料的行为。我错过了什么吗?

I don't know if this is a bug with Node or V8, but if I run the following code the node process leaks memory. The GC never seems to kick in and in a few seconds it's consuming >1GB of memory. This is unexpected behavior. Am I missing something?

这是代码:

for(;;) { console.log(1+1); }

显然,这是一个有点人为的情况,但我可以看到一个问题永远不会释放内存的长时间运行过程。

Obviously, this is a little bit of a contrived situation, but I can see an issue with a long-running process that would never free memory.

编辑:我尝试了v0.5.10(不稳定)和v0.4.12(稳定版),不稳定版本执行了好一点 - 稳定版本只是停止输出到控制台但继续占用内存,而稳定版本继续执行并消耗内存而不会暂停。

I tried both with v0.5.10 (unstable) and v0.4.12 (stable) and the unstable version performs a little bit better---the stable version just stops outputting to the console but continues to consume memory, whereas the stable version continues executing and consuming memory without pause.

推荐答案

您通过永远不返回它来阻止node.js事件循环。

You are blocking node.js event loop by never returning to it.

当您向流node.js写入内容时,异步执行此操作:它发送写请求,在流的内部数据结构中对有关已发送请求的信息进行排队等待回调将通知它完成。

When you write something to a stream node.js does that asynchronously: it sends the write request, queues information about sent request in the stream's internal data-structures and awaits the callback that would notify it about the completion.

如果阻塞事件循环,则永远不会调用回调(因为从不处理传入事件),并且永远不会释放在流中排队的辅助数据结构。

If you are blocking event loop the callback will never be called (because incoming events are never processed) and auxiliary data structures queued in the stream will never be freed.

如果通过使用nextTick / setInterval / setTimeout不断调度自己的事件来重载事件循环,可能会发生同样的情况。

The same can probably happen if you "overload" event loop by constantly scheduling your own events with nextTick/setInterval/setTimeout.

这篇关于NodeJS在无限循环中的内存消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆