Once we begin to type that code, we already introduce bugs and allocating memory without knowing it. How we manage them can make or mar our software.

In this post, we will learn, using examples, about memory leaks in Nodejs and how we can solve them.

In our effort to understand what a memory leak is, let’s first understand the memory model in JavaScript. This memory model visualizes how a JavaScript program is mapped in the RAM during execution.

Let’s take a look.

Memory Model

JavaScript has three portions of memory assigned to a program during execution: Code Area, Call Stack, and Heap. These combined are known as the Address Space of the program.

Image for post

Code Area: This is the area the JS code to be executed is stored.

Call Stack: This area keeps track of currently executing functions, perform computation, and store local variables. The variables are stored in the stack in a LIFO method. The last one in is the first out. Value data types are stored here.

For example:

var corn = 95
let lion = 100

Image for post

Here, corn and lion values are stored in the stack during execution.

Heap: This is where JavaScript reference data types like objects are allocated. Unlike stack, memory allocation is randomly placed, with no LIFO policy. And to prevent memory “holes” in the Heap, the JS engine has memory managers that prevent them from occurring.

class Animal {}// stores `new Animal()` instance on memory address 0x001232
// tiger has 0x001232 as value in stack
const tiger = new Animal()// stores `new Object()` instance on memory address 0x000001
// `lion` has 0x000001 as value on stack
let lion = {
    strength: "Very Strong"
}

Image for post

Here, lion and tiger are reference types, their values are stored in the Heap and they are pushed to the stack. Their values in stack hold the memory address of the location in Heap.

#node #javascript #web-development #developer

Understanding Nodejs’s Memory Model, with Examples
6.95 GEEK