Join the DZone community and get the full member experience.Join For Free
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.
The Problem With Browsers
Be wary with circular references for Internet Explorer and Firefox users.
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.
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.
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.
Opinions expressed by DZone contributors are their own.