You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<b><a href="#table-of-contents">↥ back to top</a></b>
3901
3901
</div>
3902
3902
3903
-
#### Q. What are the types of memory leaks in node.js
3903
+
## Q. What are the types of memory leaks in node.js?
3904
+
3905
+
A memory leak is a condition that occurs when a program doesn\'t release the memory it allocates. For instance, the system assigns memory locations to store values for the variables that we declare inside our program.
3906
+
3907
+
High-level programming languages such as JavaScript utilize automatic memory management, known as garbage collection. Garbage collection allocates the memory to a variable once we declare it and reclaims the memory once it is no longer needed. Unfortunately, even though JavaScript uses a garbage collector to release the memory, sometimes determining whether to free the memory or not is undecidable.
3908
+
3909
+
The common causes of Memory Leaks in Node.JS are:
3910
+
3911
+
**1. Global variables:**
3912
+
3913
+
This is one of the most common causes of leaks in Node. Due to the nature of JavaScript as a language, it is very easy to add to global variables and resources. If these are not cleaned over time, they keep adding up and eventually crash the application.
console.log("Server listening to port 3000. Press Ctrl+C to stop it.");
3928
+
```
3929
+
3930
+
**2. Closures:**
3931
+
3932
+
Closures memorize their surrounding context. When a closure holds a reference to a large object in heap, it keeps the object in memory as long as the closure is in use.
3933
+
3934
+
This implies easily ending up in situations where a closure holding such a reference can be improperly used leading to a memory leak.
3935
+
3936
+
**3. Timers & Events:**
3937
+
3938
+
The use of setTimeout, setInterval, Observers, and event listeners can cause memory leaks when heavy object references are kept in their callbacks without proper handling.
3939
+
3940
+
**4. Multiple references:**
3941
+
3942
+
If you reference the same object from multiple objects, it can lead to a memory leak if one of the references is garbage collected while the other one is left dangling.
3904
3943
3905
3944
<div align="right">
3906
3945
<b><a href="#table-of-contents">↥ back to top</a></b>
3907
3946
</div>
3908
3947
3948
+
## Q. How to prevent memory leaks in Node.js?
3949
+
3950
+
Tools to help debug memory leaks:
3951
+
3952
+
**1. Node-heapdump:**
3953
+
3954
+
The node-heapdump module is good for post-mortem debugging. It generates heap dumps on your SIGUSR2. To help catch bugs easily in a development environment, add node-heapdump as a dependency to your project like so:
3955
+
3956
+
```js
3957
+
constheapdump=require("heapdump");
3958
+
3959
+
heapdump.writeSnapshot(function (err, filename) {
3960
+
console.log("Sample dump written to", filename);
3961
+
});
3962
+
```
3963
+
3964
+
**2. Clinic.js:**
3965
+
3966
+
Clinic.js is a handy toolset to diagnose and pinpoint performance bottlenecks in your Node applications. The Clinic.js HeapProfiler uses flame graphs to highlight memory allocations. You can use it with tools such as AutoCannon to simulate HTTP load when profiling.
3967
+
3968
+
**3. The process.memoryUsage method:**
3969
+
3970
+
The process.memoryUsage method provides a simple way of monitoring memory usage in your Node applications.
3971
+
3972
+
The method returns an object with the following properties:
3973
+
3974
+
* **rss:**, or resident set size, refers to the amount of space occupied in the main memory for the process, which includes code segment, heap, and stack. If your RSS is going up, there is a likelihood your application is leaking memory
3975
+
* **heapTotal:**, the total amount of memory available for JavaScript objects
3976
+
* **heapUsed:**, the total amount of memory occupied by JavaScript objects
3977
+
* **external:**, the amount of memory consumed by off-heap data (buffers) used by Node; this is where objects, strings, and closures are stored
3978
+
* **arrayBuffers:**, the amount of memory allocation for ArrayBuffers and SharedArrayBuffers (the external memory size also includes this memory value)
3979
+
3980
+
**Example:**
3981
+
3982
+
```js
3983
+
console.log(process.memoryUsage());
3984
+
```
3985
+
3986
+
Output:
3987
+
3988
+
```js
3989
+
{
3990
+
rss:4935680,
3991
+
heapTotal:1826816,
3992
+
heapUsed:650472,
3993
+
external:49879,
3994
+
arrayBuffers:17310,
3995
+
}
3996
+
```
3997
+
3998
+
**4. Node Inspector:**
3999
+
4000
+
Node Inspector is a debugger interface for Node applications. Run Node with the --inspect flag to use it, and it starts listening for a debugging client. It is one of the simplest ways of capturing heap snapshots with Chrome DevTools.
4001
+
4002
+
**5. Chrome DevTools:**
4003
+
4004
+
Chrome offers a range of tools to help debug your memory and performance issues, including allocation timelines, sampling heap profiler, and heap snapshots etc.
4005
+
4006
+
## Q. How Garbage collection works in Node.JS?
4007
+
4008
+
The V8 uses a scheme similar to the Java Virtual Machine and divides the memory into segments. The thing that wraps the scheme concept is known as Resident Set, which refers to the portion of memory occupied by a process that is held in the RAM.
4009
+
4010
+
* **Stack**: Stores static data, method and function frames, primitive values, and pointers to stored objects. The stack is managed by the operating system.
4011
+
4012
+
* **Heap**: Stores objects. Because everything in JavaScript is an object this means all dynamic data like arrays, closures, etc. The heap is the biggest block of memory and it\'s where Garbage Collection (GC) happens.
4013
+
4014
+
* **Code Segment**: the actual code is being executed.
Garbage collection frees up memory in the Heap used by objects that are no longer referenced from the Stack, either directly or indirectly. The goal is to create free space for creating new objects. Garbage collection is generational. Objects in the Heap are grouped by age and cleared at different stages.
4021
+
4022
+
**Mark-and-sweep algorithm:**
4023
+
4024
+
In JavaScript, the root is the global object. The garbage collector start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.
4025
+
4026
+
<div align="right">
4027
+
<b><a href="#table-of-contents">↥ back to top</a></b>
0 commit comments