How to use the Memory panel to find memory leaks in JavaScript?
Memory leaks in JavaScript applications can lead to a gradual decrease in performance, freezes, and even complete crashes of the browser tab. To diagnose and find such issues, the Memory tab in the developer tools is used. It allows you to take snapshots of the memory state at specific points in time and deeply analyze the objects that occupy RAM and are not removed by the garbage collector.
The main tool for analysis is the heap snapshot, which can be obtained by selecting the Heap snapshot option and clicking the snapshot creation button. It is recommended to take at least two snapshots for comparison: the first in the initial state of the application, and the second after performing specific user actions that potentially cause a leak, such as opening and closing a modal window.
After creating the snapshots, you can switch the display mode from Summary to Comparison to see the difference between memory states. This allows you to filter out objects that were created and remained in memory, but were not destroyed after operations completed. Pay attention to the Delta column, which shows the growth in the number of objects of a specific class.
By clicking on a suspicious object, you can examine the so-called retention paths at the bottom of the screen. The path graph shows which exact references are keeping the object in memory and preventing the garbage collector from clearing it. By finding this root reference, you can fix the code by removing unnecessary event handlers or global references that block the release of resources.