DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Memory Management and Garbage Collection in JavaScript

Memory Management and Garbage Collection in JavaScript

Read on to learn how to more effectively prevent data leaks and handle your data using memory management and garbage collection.

Raghuraman Kesavan user avatar by
Raghuraman Kesavan
·
Aug. 17, 17 · Analysis
Like (4)
Save
Tweet
Share
42.34K Views

Join the DZone community and get the full member experience.

Join For Free

Memory Management and garbage collection in JavaScript is a slightly unfamiliar topic since in JavaScript we are not performing any memory operations explicitly, however, it is good to know how it works.

In the low-level languages like C, developers need to manually allocate and deallocate the memory using the malloc(), calloc(), realloc(), and free() methods. In the high-level languages like Java and JavaScript, we don't need to explicitly allocate or release memory. JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

Memory Life Cycle:

Irrespective of any language (high-level or low-level), memory life cycle will be similar to what is shown below.

Memory Life cycle

In the high-level languages, we will just read and write to the memory explicitly (Use Memory). In the low-level languages, developers need to take care to explicitly perform all three steps.

Since allocation and deallocation happen automatically, that doesn't mean developers don't care about memory management. Poor coding may lead to memory leaks, which is a condition where memory is not released even though it is no longer used by the application. So it is very important to learn more about memory management.

Memory Allocation in JavaScript:

When declaring a variable, JavaScript will automatically allocate the memory for the variables.

var numberVar = 100;                // allocates memory for a number
var stringVar = 'node simplified';  // allocates memory for a string 
var objectVar = {a: 1};             // allocates memory for an object
var a = [1, null, 'abra'];          // allocates memory for the array
function f(a) {
  return a + 2;
} // allocates memory for a function 

When the memory is no longer needed anymore, then the allocated memory will be released. Memory leaks, and most memory related issues, occur while releasing memory. The hardest part is finding the memory which is no longer needed and tracking it down with the garbage collector.

Garbage Collection:

Garbage collection is the process of finding memory which is no longer used by the application and releasing it. To find the memory which is no longer used, a few algorithms will be used by the garbage collector, and in this section, we will look into the main garbage collection algorithms and their limitations. We will look into following algorithms:

  • Reference-counting garbage collection.
  • Mark-and-sweep algorithm.

Reference-Counting Garbage Collection:

This is the most important garbage collection algorithm. If in reference counting algorithms, there are no references to an object, it will be automatically garbage collected. This algorithm considers zero referencing object as an object that is no longer used by the application.

Example:

var o = { a: { b: 2 } }; 
// 2 objects created. One is referenced by the other as one of its properties.
// Obviously, none can be garbage-collected

o = 1;     // what was the 'a' property of the object originally in o 
           // has zero references to it. It can be garbage collected.

Limitation: Cycles

function func() {
  var o = {};
  var o2 = {};
  o.a = o2; // o references o2
  o2.a = o; // o2 references o
  return 'true';
}

func();

Consider the above code snippet in which o is referenced to o2 and o2 is referenced to o and it creates a cycle. When the scope goes out of the method, then these two objects are useless. However, the garbage collector is unable to free the memory since those two still got the reference to each other. It leads to memory leaks in the application.

Mark-and-Sweep Algorithm:

The garbage collector uses this algorithm to free memory when an object is unreachable, rather than a zero referencing object.

The garbage collector will first find all the global objects or root objects and will find all the references to these global objects and references to the reference object, and so on. Using this algorithm, the garbage collector will identify the reachable and unreachable objects. All the unreachable objects will be automatically garbage collected.

This article is originally published from Node Simplified. Take a look into Top Javascript Tips and Tricks.

If you enjoyed this article,  Hit Like & please share with your developer friends. Thanks for reading. 

Memory (storage engine) Garbage (computer science) garbage collection JavaScript Object (computer science) Algorithm

Published at DZone with permission of Raghuraman Kesavan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • HTTP vs Messaging for Microservices Communications
  • Reliability Is Slowing You Down
  • Cloud Performance Engineering
  • Spring Boot vs Eclipse MicroProfile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: