Garbage Collection
Garbage collectors are used in releasing memory. Once the engine recognizes that a variable, object, or function is not needed anymore, it releases the memory it occupied. The main issue here is that it is very difficult to predict accurately whether a particular variable, object, or function is needed anymore or not. Some algorithms help to find the moment when they become obsolete with great precision.
Reference-counting garbage collection
It frees the memory allocated to the objects that have no references pointing to them. However, the problem with this algorithm is that it doesn’t understand cyclic references.
Example: In this example, the game and boy both reference each other. Thus, the algorithm won’t release the allocated memory. Setting them to null won’t make the algorithm realize that they can’t be used anymore, leading to no release of allocated memory.
Javascript
let game = { name: 'cricket' , }; let boy = { name: 'Ram' , } game.boy = boy; boy.game = game; boy = null ; game = null ; |
Memory Management in JavaScript
Memory management in JavaScript is handled automatically by the runtime environment, typically the JavaScript engine in web browsers or Node.js. JavaScript uses a garbage collector to manage memory and ensure that developers do not need to manually allocate or deallocate memory.
Contact Us