How can I handle Eradicating Memory Leaks In Javascript?

If you are wondering why your Javascript application might be suffering from severe slowdowns, poor performance, high latency or frequent crashes and all your painstaking attempts to figure out the problem were to no avail, there is a pretty good chance that your code is plagued by ‘Memory Leaks’. Memory leaks are fairly common as memory management is often neglected by developers due to the misconceptions about automatic memory allocation and release in modern high level programming languages like javascript. Failure to deal with javascript memory leaks can wreak havoc on your app’s performance and can render it unusable. The Internet is flooded with never-ending complex jargon which is often difficult to wrap your head around. So in this article, we will take a comprehensive approach to understand what javascript memory leaks are, its causes and how to spot and diagnose them easily using chrome developer tools.

What are Javascript Memory Leaks?

A Memory leak can be defined as a piece of memory that is no longer being used or required by an application but for some reason is not returned back to the OS and is still being occupied needlessly. Creating objects and variables in your code consumes memory. Javascript is smart enough to figure out when you won’t need the variable anymore and will clear it out to save memory. A Javascript memory leak occurs when you may no longer need an object but the JS runtime still thinks you do. Also, remember that javascript memory leaks are not caused by invalid code but rather a logical flaw in your code. It leads to the diminished performance of your application by reducing the amount of memory available for it to perform tasks and could eventually lead to crashes or freezes.

Before diving deeper into memory leaks, it is crucial to have a sound understanding of memory cycles, memory management systems and garbage collector algorithms.

What is Memory Cycle?

A ‘memory’ consists of a series of flip-flops, which is a 2-state(0 & 1) circuit composed of 4 to 6 transistors. Once flip-flop stores a bit, it will continue to retain it until it is rewritten with the opposite bit. So memory is nothing but an array of reprogrammable bits. Each and every single piece of data being used in a program is stored in the memory.

Memory Cycle is the complete sequence of events for a unit of memory to go from an idle/free state through a usage(read or write) phase and back to the idle state. Memory cycle can be broadly broken down to 3 major steps –

  1. Memory Allocation: memory is allocated by the OS to the program during execution as per need. In low level languages like C and C++ this step is handled by the programmer but in high level languages like javascript, this is done on its own by the automatic memory management system. Some examples of memory allocation in javascript –
       var n = 5; // allocates memory for a number
       var s = 'Hello World'; // allocates memory for a string
       var obj = { // allocates memory for an object
           a: 100,
           b: "some string",
           c: null,
       };
       var arr = [100, "some string", null]; // allocates memory for the array
       function foo(x, y) { // allocates memory for a function
           return x * y;
       }
  1. Memory Usage: Program performs read and write function on the allocated memory. This can be reading or writing the value of a variable, an object or even passing an argument to a function.
  2. Memory Release: when the task is finished and allocated memory is no longer needed, it is released and made free for new allocation.

The third step of the memory cycle is where the complications lie. The most difficult challenge here is to determine when “the allocated memory is not needed any longer and should be freed”. This is where memory management systems and their garbage collector algorithms come to the rescue.

Memory Management Systems – Manual vs Automatic

Memory Management is the process of assigning memory blocks to various programs during execution at their request, and free it for reallocation when no longer needed. Different programming languages use different approaches depending upon their complexity to deal with memory management.

  • Low-level languages like Pascal, C and C++, have manual memory management system where the programmer must manually/explicitly allocate memory when needed and then free up the memory after it has been used by the program. For example, C uses malloc() and calloc() to reserve memory, realloc() to move a reserved block of memory to another allocation and free() to release memory back to the system.
  • High-level programming languages like Javascript and VB have an automated system that allocates memory each time you create an entity like – an object, an array, a string, or a DOM element and automatically frees it up when they are not used anymore, by a process called garbage collection. Memory leaks happen when your program is still consuming memory, which ideally should be released after the given task was completed. For some reason, the garbage collector fails to serve its purpose and the program refuses to release the memory, which keeps on being consumed without any need for it to happen.

Garbage Collectors

Garbage collectors execute the process of finding memory which is no longer in use by the program and releasing it back to the OS for future reallocation. To find the memory which is no longer being used, garbage collectors rely on algorithms. Though the garbage collection method is highly effective, it is still possible for Javascript memory leaks to occur. The main cause for such leaks is very often- ‘unwanted reference’. The primary reason for this is the fact that garbage collection process is based on estimations or conjectures, as the complex problem of whether some memory needs to freed cannot be determined by an algorithm correctly at every instance.

Before moving further, let’s take a look at the two most widely used GC Algorithms

As we discussed earlier, any garbage collection algorithm must perform 2 basic functions. It must be able to detect all the memory that is no longer in use and secondly, it must free/deallocate the space used by the garbage objects and make it available again for reallocation in future if needed.

The 2 most popular algorithms are –

  1. Reference count
  2. Mark and Sweep


  • Reference Count Algorithm

This algorithm relies on the notion of ‘reference’. It is based on counting the number of reference to an object from other objects. Each time an object is created or a reference to the object is assigned, it’s reference count is increased. In JavaScript every object has an implicit reference to its prototype and explicit reference to its property values.

Reference count algorithm is the most basic garbage collector algorithm, It reduces the definition of “an object is not needed anymore” to “an object has no other objects referencing it”. An object is considered garbage collectible and deemed to be no longer in use if there are zero references pointing to it.

Read more from the original source: Eradicating Memory Leaks In Javascript

#selenium #testing #css3 #javascript #angular.js #html5

3 Likes10.40 GEEK