How does JavaScript manages memory?

When we write any code in Js, memory gets allocated to our variables, functions that are been used. Depending upon the dataTypes, variables are allocated with memory either in stack (primitive datatypes like string, number, boolean) or heap (non primitive datatypes like objects, arrays, functions).
Once these variables are no more required in a code block, its necessary that the memory used by these variables in freed and made available for the next execution. This work of freeing the memory is done by Garbage collector!
JavaScript manages memory through a combination of Automatic allocation (allocating memory automatically without the need of the developer to do so) and garbage collection. In low level languages like C or C++, developer manually needs to clean up the space that is no longer used unlike JS or python!
Lets sweep it out with Garbage Collector!
Garbage collection (GC) in JavaScript is performed during runtime.
Lets see what does this GC does
- GC identifies and reclaims memory that is no longer in use by the application. This helps to free up resources that can be reused for new allocations.
- By automating the process of memory management, GC allows developers to focus on writing code without having to manually allocate and deallocate memory.
- GC helps prevent memory overflow and memory leaks by cleaning up objects that are no longer reachable from the root references (e.g., global variables, active function calls).
- Efficient garbage collection can enhance overall application performance by ensuring that memory is used optimally, which can reduce the overhead of memory allocation and deallocation.
Now, lets see when does this GC actually gets started to do its job. (Timmings of GC)
- Garbage collection happens during the execution of the program. By continuously monitoring memory and cleaning up unused allocations, GC helps prevent the application from exhausting available memory, which could lead to crashes or degraded performance.
- GC can also run periodically or when certain memory thresholds are reached.
Now whats Memory overflow?
Memory overflow occurs when a program tries to use more memory than is available in the system, leading to failures such as crashes or unexpected behavior. It often results from poor memory management practices and can manifest in several ways:
Types of Memory Overflow
- Stack Overflow: This occurs when the call stack (used for function calls and local variables) exceeds its limit, typically due to deep or infinite recursion.Symptoms include crashes or exceptions indicating a stack overflow error.
function recursiveFunction() {
return recursiveFunction(); // Infinite recursion
}
recursiveFunction(); // This will eventually cause a stack overflow.
2. Heap Overflow: This happens when the heap memory (used for dynamic memory allocation) runs out of space. It can result from excessive memory allocation without proper deallocation, leading to memory leaks. Symptoms may include slow performance, crashes, or out-of-memory errors.
let array = [];
while (true) {
array.push(new Array(1000000).fill("data")); // Allocating too much memory
}
Why Does memory overflow Happen (Causes)
- Continuously allocating large amounts of memory (e.g., large arrays or objects) without releasing unused memory can lead to overflow.
- Programs that enter infinite loops or recursively call functions without a base case can exhaust stack or heap space.
- Memory Leaks: Failing to release memory for objects that are no longer needed can gradually consume all available memory, leading to overflow.
By properly managing the causes, memory overflow can easily be avoided!
Memory Leaks
A memory leak in JavaScript occurs when the program allocates memory for objects but fails to release that memory when it’s no longer needed. This leads to increased memory consumption over time, which can degrade performance and ultimately cause the application to crash due to running out of memory.
Why does Memory Leak happens (Causes)
- Global Variables: Variables declared without
var
,let
, orconst
become global. They persist for the lifetime of the application, preventing the garbage collector from reclaiming the memory they occupy.
function leakGlobal() {
leakedVariable = "I'm global!"; // No var/let/const
}
leakGlobal();
2. Unreleased Event Listeners: When you attach event listeners to DOM elements and do not remove them, the event keeps listening, preventing it to get colleted by the gc.
3. Closures: Closure can inadvertently retain references to outer scope variables even after they are no longer needed.
Consequences of Memory Leaks
- Performance Degradation: As memory consumption increases, the application may slow down due to increased garbage collection cycles or reduced memory availability.
- Crashes: Eventually, if memory consumption continues unchecked, the application can crash due to exhaustion of available memory.
- User Experience: Memory leaks can lead to unresponsive UI or delays, negatively impacting the user experience.
Preventing Memory Leaks
- Scope Management: Use local variables as much as possible and limit the use of global variables.
- Remove Event Listeners: Always clean up event listeners when they are no longer needed.
- Use Weak References: Utilize
WeakMap
orWeakSet
to hold references that do not prevent garbage collection. - Avoid Unnecessary Closures: Be cautious with closures and avoid retaining large objects in memory longer than needed.
- Profiling and Monitoring: Use browser developer tools to monitor memory usage and identify potential leaks. Tools like Chrome’s Memory panel can help visualize memory consumption and find leaks.
Conclusion:
Memory is a crucial and limited resource, making garbage collection (GC) vital for effective memory management. GC automates the process of freeing unused memory and optimizing resource usage, which improves application performance and reliability. It helps prevent issues like memory leaks and memory overflow, which can arise from poor coding practices and lead to application crashes or slowdowns. Therefore, it’s important to be aware of the causes of memory leaks to avoid them.