What is Heap Memory?

Before we begin with the explanation of JavaScript heap out of memory let us understand what is a heap?

Heap is simply an area where memory is allocated or freed in no particular order. This happens when creating an object with an operator new or something similar.

This is contrasted with the stack, where memory is freed based on the first entry and the last exit. In other words, it is a chunk of memory allocated from the operating system by the memory manager used by the process.

The malloc() in calls then grab memory from that heap instead of dealing directly with the operating system.

A  heap is a place in memory where memory is allocated in order. Further, individual data items allocated on the heap are usually deallocated asynchronously from each other. Any such data item is freed when the program explicitly frees the associated pointer. Moreover,  this can result in a fragmented heap.

In contrast, only data from the top or from the bottom, (depending on how the stack works) can be freed. So, it causes the data items to be freed in the reverse order in which they were allocated.

Dont get mistaken with the term ‘heap’

Term heap means the allocation of memory, not in terms of data structure (the term has multiple meanings).

Every developer faces memory leaks which is a problem eventually. Memory can be leaked even working with memory-managed languages.

Leaks can be caused due to problems like-

  • High latency
  • Slowdowns
  • Crashes
  • And even problems with other applications.

When JavaScript heap out of memory occurs?

JavaScript heap out of memory occurs when there is memory leak.

A memory leak is a scenario in application when- an object in the program is holding memory that is allocated to it, even after the program execution is completed.

Subsequently, the memory that the object is holding will not be referred even later on in the program. Consequently, creates unnecessary memory blockage. This degrades the performance of the application, as the application may run out of memory, when needed.

In a way, JavaScript heap out of memory exceptions can be explained as memory which was used by the program in the past, while execution but it is not required currently by the program yet the object is still holding that chunk of memory, unnecessarily and the memory is yet to be released by the object.

JavaScript is designed to reduce memory leaks

JavaScript has a protocol to reduce such memory leaks, which is called Garbage Collection. With this, the objects and variables are cleared from memory.

As JavaScript is called garbage collected language. It periodically checks for pieces of memory that can be reused. Therefore, preventing memory leaks.

This gives rise to a question that, “Even after garbage collection, what makes the program have memory leak issues”

So to answer this let’s understand the process of garbage collection in JavaScript.

Understanding garbage collection in JavaScript

As memory is automatically allocated, by the method of Dynamic memory allocation each time you create an object or a DOM element in JavaScript.

Whereas, Garbage Collection is a background process of the JavaScript engine, which looks for unreachable objects, removes these unreferenced objects, and frees the underlying memory.

So now a memory leak can occur when an object that is to be cleaned in a garbage collection cycle, but that particular object stays reachable from an object by an unused reference.

This means the object which is holding a reference to the object which is supposed to be cleared from the memory may not use that reference in the coming execution

This results in excessive memory use and can lead to poor performance.

How to make sure if the code is leaking memory?

As memory leaks from the program are often hard to notice and to reciprocate every time. The leaking JavaScript code is not considered invalid, and the browser will also not throw any error while running it. As the memory leak is not bound to happen every time you run the program.

If you notice that the performance of your page is getting down, there are the browser’s built-in tools that can help to determine if a memory leak exists and what objects are causing it.

The biggest problem with such memory leaks is that they’re in-born code, which makes code flawed. These are not errors or exceptions with respective messages that you can rectify.

Memory leaks are uncertain because they are generated from valid code that was written as per requirement, which makes the runaway, memory-leaking code seem intentional for the machine.

They’re definitely not features

However, if the application is slowing down or even crashing unexpectedly, that’s the first clue that you may have a memory leak issue.

The 4 Most Common Scenario of Memory Leaks

Referencing undeclared Variable

When an undeclared variable is used as a reference to a local scoped variable, it will create a global variable, which will be used within the global scope. The reference to the global variable will also be global. As we know the global reference, will be preserved in memory till the end this will also prevent the object from Garbage Collection

This causes memory leak or we can say memory blockage from the local scope into the global scope.

The easiest way to avoid this issue is to make use of the “ strict” directive. With this Strict directive, we cannot use undeclared variables as reference to local variables.

If you need to use or declare a global variable inside a function, then you can explicitly attach the variable to the window object.

Cyclic reference create problems

Cycles in programming terms mean a deadlock kind of reference.

There is a limitation when we use cycles of such references.

In the following example, two objects are created and they reference one another, thus creating a cycle which is a deadlock.

These objects will go out of scope after the function call is completed, so they are effectively useless and their memory usage could be easily freed. However, the system’s reference-counting algorithm will consider that since both the objects are being referenced at least once, neither of them can be garbage-collected, thus resulting in memory blockage.

function f() {

var o1 = {};

var o2 = {};

o1.p = o2; // o1

references o2

o2.p = o1; // o2

references o1. This creates a cycle.

}

f();

Closures

Variables declared within the function scope will be cleaned up after the function execution is completed and if there aren’t any references left outside of the function pointing to these variables.

The system will keep the variables referenced and alive although the function has finished executing and its execution context and variable environment are long gone.

So to prevent this kind of memory Leak

  • Understand when the function closure has been created and which objects are retained by it at the time of Garbage collection,
  • Also, understand closure’s expected lifespan and usage, specifically if it is used as a callback function, as that will give rise to more such memory allocations within the function.

Subscription to Event listeners

An event listener will preserve all variables captured in its scope from being garbage collected. As these variables are destroyed when the event listener is destroyed

Once subscribed, the event listener will remain in effect until:

It is explicitly removed/unsubscribed

Or the DOM element associated with the event is removed.

For some specific types of events that are based on the user inputs, it is expected to keep subscribed to such events until a user leaves that page.

In order to prevent this, we should always unsubscribe from the event listener, once it is no longer needed. This will save us from keeping objects/variables in memory for a long time.

Now that we have understood the process measures for memory allocation and also to prevent the JavaScript heap out of Memory issues.

Let’s take a look at how to detect these memory leak issues.

How to detect heap overflow

Often the following error occurs, when there is an issue of memory leak:

FATAL ERROR: CALL_AND_RETRY_LAST

Allocation failed — JavaScript heap out of memory

With this error, the application gets terminated immediately, and if the application is hosted on an HTTP server, it’ll stop serving requests.

In order to avoid this scenario, It is advisable to use cluster and v8 core libraries of the node.

Cluster provides the user to take advantage of multi-core systems, and launch a cluster of processes to handle some tasks.

V8 exposes APIs to the frontend, only if itis specific to the version of V8 built into the Node.js binary.

So now we can conclude on the reasons for memory leak, which is a heap out of memory issue and its preventive measure.