检测代码中的node.js/javascript内存泄漏 [英] Detect node.js/javascript memory leak in code

查看:52
本文介绍了检测代码中的node.js/javascript内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有某些代码有效,但是其中存在内存泄漏.

I have some code that is working, however it has a memory leak in it.

在node.js中跟踪内存泄漏有哪些好的策略?

What are some good strategies for tracking memory leaks in node.js?

寻找此类泄漏时应遵循什么步骤?

What steps should I follow when looking for such leaks?

如何跟踪代码中的泄漏?

How can I track the leak in my code?

谢谢

推荐答案

您可以通过分析应用程序的内存使用情况来解决这一问题.

You can figure this out by profiling the memory usage of your application.

JavaScript对象是在堆上分配的,因此您需要一个可以转储堆的工具.获取堆转储后,您可以对其进行检查,并查看给定对象(或函数)的实例数.

Javascript objects are allocated on the heap, so you'll want a tool that can dump the heap. After acquiring a heap dump you can inspect it and see how many instance of a given object (or function) exist.

例如,对于您的代码,您知道在用户连接时都会创建一个套接字.在连接三个用户时转储堆应显示〜3个套接字.在这些用户断开连接之后转储堆应该显示〜0个套接字.

E.g., for your code you know you create a socket whenever a user connects. Dumping the heap while three users are connected should show ~3 sockets. Dumping the heap after those users disconnect should show ~0 sockets.

您实际上可以将Chrome堆转储分析器与Node.js堆转储一起使用.

You can actually use the Chrome heap dump analyzer with Node.js heap dumps.

允许您进行Node.js堆转储并在chrome中对其进行检查的项目: https: //github.com/bnoordhuis/node-heapdump

Project that allows you to take Node.js heap dumps and inspect them in chrome: https://github.com/bnoordhuis/node-heapdump

仅供参考,函数将显示在(closure)部分下的堆转储中.

Just fyi, functions are going to show up in the heap dump under the (closure) section.

您需要确保为函数命名(即使它们不需要名称),以便它们在堆转储中显示为有用的东西.

You'll want to make sure you name your functions (even if they don't need a name) so they show up as something useful in the heap dump.

例如,类似

function() { }

function() { }

只会在堆转储中显示为function().哪里:

will just show up as function() in the heap dump. Where as:

function taggedFunction() { }

function taggedFunction() { }

在堆转储中将显示为function taggedFunction().如果创建100个aggedFunction,那么堆转储中将看到taggeFunction 100次.基本上,命名功能可以让您确定是否继续创建和泄漏它们.

will show up as function taggedFunction() in the heap dump. If you create 100 taggedFunctions then you'll see taggeFunction in the heap dump 100 times. Basically, naming your functions lets you figure out if you keep creating and leaking them.

这篇关于检测代码中的node.js/javascript内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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