Have you ever left a web app opened in a tab for a couple of hours to come back and see this screen? In this post we will learn how to use the Chrome DevTools to find memory leaks.
Visualize using Timeline
Can you spot a problem with the following code snippet?
Don’t worry if you can’t figure it out, the issue is not so obvious. To diagnose if an application has a memory leak, you can use the Performance section in Chrome DevTools. In the above example we want to check if continuous usage of the application (adding/removing tasks) causes unexpected increase of memory usage. To test this we can record the memory usage while adding and removing a task several times. We expect that when we add a task the memory usage increases and when we remove it – the memory usage drops back to the previous level.
As seen on the screenshot above the nodes and listeners progressively increase and never drop while the
expected outcome is a graph similar to the JS Heap line above.
Discover detached DOM using Heap Snapshots
When it comes to finding where the problem originates the Memory section in Chrome DevTools comes in handy. With a couple of
snapshots we can find which parts of the application use more memory than expected and whether we have any detached DOM elements:
Turns out our Task’s destroy method has a bug – we call the DOM removemethod, but we still keep a reference to the DOM element, so it’s never collected. When we get that fixed and perform the same test in the Performance tab, we’ll see the pattern we want:
Here you can get the fully working examples:
Here's one way we could sample memory usage and feed it into a monitoring tool (like TrackJS). This example uses requestAnimationFrame to periodically check the memory usage and record an error if it has crossed either an absolute or relative threshold.
Open Chrome on your computer..
Click Security and Privacy..
Click Site settings..
Press F12 to open the developer tools and go to the Memory Tab..
Pick a feature or a part of your app that you want to inspect for leaks. ... .
Do the action (for example opening a dialog) you want to check for memory leaks once, so potential global services can be loaded. ... .
Now select Record Allocation Timeline and press Start..