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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • AI’s Role in Everyday Development
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Agile and Quality Engineering: A Holistic Perspective
  • How Trustworthy Is Big Data?
  1. DZone
  2. Coding
  3. Languages
  4. Resolving Circular Reference Related Memory Leaks in JavaScript

Resolving Circular Reference Related Memory Leaks in JavaScript

JavaScript developers must understand the root cause of memory leaks and take reasonable measures to deal with them. Circular references are one of the main causes of memory leaks, especially in older browsers.

By 
Ryan Kh user avatar
Ryan Kh
·
Feb. 08, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
18.5K Views

Join the DZone community and get the full member experience.

Join For Free

JavaScript is a dynamic, garbage collection programming language. It allocates memory for objects when they are first created and releases that memory after any references to them are destroyed. This is one of the biggest factors that differentiates JavaScript from C++ and other C-based programming languages. It is also one of the main reasons JavaScript is widely used for recurring web-based applications, such as online stores and e-commerce platforms like Shopify.

Unfortunately, memory isn't always properly reallocated. If object references are improperly terminated, memory leaks can develop. Over time, they can consume too much memory for the application to continue to run seamlessly.

JavaScript developers must understand the root cause of memory leaks and take reasonable measures to deal with them. Circular references are one of the main causes of memory leaks, especially in older browsers.

The Problem With Browsers

Be wary with circular references for Internet Explorer and Firefox users.

In JavaScript, browsers record references to every object. If all references to an object are broken, the object is destroyed and memory is reallocated back to the heap.

Unfortunately, the memory isn’t always returned to the heap if references with other objects are formed. Microsoft provides a brief overview of the issues that arise if references to DOM aren’t broken.

"As described in detail in Understanding and Solving Internet Explorer Leak Patterns, the JScript garbage collector in previous versions of Windows Internet Explorer manages the lifetime of JScript objects but not of DOM objects. As a result, the JScript garbage collector cannot break circular references between DOM objects and JScript objects, and memory leaks occur. In Microsoft Internet Explorer 6, these circular references are broken when the Windows Internet Explorer process terminates. In Windows Internet Explorer 7, these circular references are broken when users navigate away from the page that contains the leaks."

- Microsoft Documentation

In other words, a circular reference occurs if two separate objects pass references to each other. Google Chrome does not count circular references, so objects are usually destroyed when the object is no longer needed. However, Internet Explorer and Firefox use circular references as part of their reference count.

As a result, objects may continue to exist and consume memory long after they are needed. Newer versions of these browsers are better at discounting circular references, but issues still occur. Developers need to take additional steps to prevent memory leaks.

Before JavaScript developers can resolve memory leaks, they must obviously identify them. They must monitor their code carefully for references between unrelated objects. IBM provides an example in one of their tutorials on the topic:

HTML
 




x


 
1
<html>
2
  <body>
3
    <script type="text/javascript">
4
      document.write("Circular references between JavaScript and DOM!");
5
      var obj;
6
      window.onload = function(){
7
        obj=document.getElementById("DivElement");
8
        document.getElementById("DivElement").expandoProperty=obj;
9
        obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
10
      };
11
    </script>
12
    <div id="DivElement">Div Element</div>
13
  </body>
14
</html>



Fortunately, there are some solutions to circular reference related memory leaks. The most straightforward approach is to assign the null value to the elem property. This breaks the circular link and keeps the handler from referencing the DOM any longer. Without a reference to DOM, the browser is instructed to stop reserving memory for the object.

Ilya Kantor of JavaScript Tutorial states that the following application can be resolved by creating and calling the following function:

JavaScript
 




xxxxxxxxxx
1


 
1
function setHandler() {
2
  var elem = document.getElementById('id')
3
  elem.onclick = function() { /* ... */ }
4
}


You can add bigString = null to your code when you want to terminate the object.

Rigorously Monitor Circular References in Your JS Code

While new browsers are more adept at resolving memory leaks caused by circular references, problems often arise with older browsers. These types of memory leaks can still occur with newer versions of Internet Explorer and Firefox as well, so it’s important to monitor code carefully to identify circular references.

Memory (storage engine) JavaScript Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Shallow and Deep Copies in JavaScript: What’s the Difference?
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!