Over the last decade, Internet access has shifted from being limited to the upper crust to practically anybody with a device capable of connecting to the internet. With more individuals using the internet, developers confront a significant difficulty in managing the application’s load and memory management. Let us see how we achieve this in Node.
Memory leaks have been the most common enemy that the IT sector has been forced to battle with every day. This is primarily due to the expanding user base and, more importantly, because of the growing codebase which is coupled with hundreds of new features added with each software release. Memory leaks can cause several issues including application slowdowns, crashes, and high latency, among other things.
Garbage Collection With Reference to Counting
This is the most rudimentary garbage collecting method. This algorithm checks whether or not the object has at least one reference. The term ‘trash’ is used if there are no references to an object. Let us have a look at how GC works in general.
Circular References Are a limitation.
Let’s imagine two objects in memory are referring to one another, establishing a cycle, but they’re not connected to the root. That is, they are no longer required in the code execution because they are outside the scope of the function. This memory must now be reclaimed. However, because the reference counting mechanism checks if an object has at least one reference pointing to it, neither of them is designated as garbage and continues to occupy memory space.
Algorithm of Mark-and-Sweep
The unreachable objects are then freed from memory by the GC. Circular references are no longer an issue. If two circularly referred items exist in the memory and can’t be reached directly or indirectly through the roots, they’re released.
Causes of Memory Leak in Node.js
- Global Variables
- Multiple References
- Timers & Events
This was all about memory management and memory management in Node.js! If you want to learn more about it, do check out the articles based on Node.js available on Codedamn, along with the course. We hope you enjoyed it; do let us know if you have any questions or recommendations in the comments section.