WeakSet
WeakSet is a collection of objects where each object can occur only once. Similar to WeakMap, the objects stored in a WeakSet are weakly held, meaning they won’t prevent garbage collection. WeakSet is useful when you need to store a collection of objects but want those objects to be garbage collected when no longer referenced elsewhere in the code.
Syntax:
let weakSet = new WeakSet();
let obj1 = {};
let obj2 = {};
weakSet.add(obj1);
weakSet.add(obj2);
Example: Efficient Event Listener Management with WeakSet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>WeakSet Example</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
}
button {
padding: 10px 20px;
border-radius: 5px;
background-color: green;
color: white;
cursor: pointer;
}
button:hover {
background-color: rgb(226, 231, 228);
color: black;
}
</style>
</head>
<body>
<div>
<img src=
"https://media.w3wiki.org/gfg-gg-logo.svg"
alt="gfg_logo">
<h2>Click the Button</h2>
</div>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<script>
// Create a WeakSet
// to store event listeners
let eventListeners = new WeakSet();
// Function to add an event
// listener to a DOM element
function addEventListener(element, eventName, callback) {
// Create a listener function t
// hat wraps the original callback
function listener(event) {
callback(event);
}
// Add the listener to the element
element
.addEventListener(eventName, listener);
// Add the listener to the WeakSet
eventListeners.add(listener);
}
// Example usage:
// Retrieve the buttons from the DOM
let button1 = document
.getElementById('btn1');
let button2 = document
.getElementById('btn2');
// Function to handle button clicks
function handleClick(event) {
alert(`Button clicked: ${event.target.textContent}`);
}
// Add event listeners to the buttons
addEventListener(button1, 'click', handleClick);
addEventListener(button2, 'click', handleClick);
// At this point, the event
// listeners are attached to the buttons
// Remove the first button from the document
let timeOutId = setTimeout(() => {
button1
.parentNode
.removeChild(button1);
clearTimeout(timeOutId)
alert('Removing Button 2');
}, 8000)
</script>
</body>
</html>
Output
How to Handle Memory Leaks in JavaScript ?
JavaScript, unlike some other programming languages, uses automatic memory management. This means the developer doesn’t have to explicitly free up memory when they’re done with it. However, memory leaks can still happen in JavaScript if objects are not properly cleaned up. A memory leak is a situation where memory is allocated for objects that are no longer being used by the program, but the garbage collector can’t reclaim that memory because the objects are still being referenced somewhere. This can lead to performance slowdowns and crashes as the application continues to run.
The benefit of Addressing Memory Leaks in JavaScript
Addressing memory leaks is crucial for maintaining the efficiency and stability of JavaScript applications and many more.
- Improved Performance: Memory leaks can gradually degrade the performance of a JavaScript application over time by consuming more memory than necessary. By addressing memory leaks, you can prevent excessive memory usage and maintain optimal performance.
- Stability: Memory leaks can lead to unpredictable behavior in an application, such as crashes or freezes, especially in long-running applications or web pages.
- Faster Page Load Times: When memory is abundant, your web pages can load faster. Handling memory leaks ensures enough memory is available for efficient page loading, leading to a better user experience.
- Reduced Resource Consumption: Memory leaks can cause your application to consume more and more memory over time.
- Enhanced User Experience: Memory leaks can negatively impact the user experience by causing slowdowns, crashes, or unexpected behavior. By handling memory leaks, you can provide a smoother and more reliable user experience, leading to higher user satisfaction and retention.
There are several approaches available in JavaScript to handle memory leak which are as follows:
Table of Content
- Clearing Event Listeners
- Avoiding Global Variables
- Managing DOM References
- WeakMap
- WeakSet