Meta, the company behind Facebook, has open sourced MemLab, a tool for finding memory leaks in JavaScript applications on Chromium-based browsers.
As the Facebook engineering team notes: “People using our web apps will often notice performance and functional correctness issues immediately. A memory leak, however, … isn’t immediately perceivable.” Instead, users will get a gradually less responsive session. The consequences of memory leaks are more severe in single-page applications (SPAs), because the user may continue to interact with the page for an extended period, and MemLab is specifically designed for this scenario.
MemLab uses Puppeteer, a Node.js library which (as its name suggests) can control Google Chrome or Chromium, by default in headless mode so that it runs from the command line. MemLab works by navigating to a page and then away from it. “We would expect most of the memory allocated by that page to also be freed — if not, it is highly suggestive of a memory leak,” the engineers explain. MemLab has some framework-specific knowledge, in particular of React, the framework created by the Facebook team which now dominates JavaScript development.
React represents the browser DOM (Document Object Model) in-memory using objects called Fibers which are stored in a tree structure. This can be a cause of “huge memory leaks,” according to the team, because “the downside of having a strongly connected graph is that if there is any outside reference pointing to any part of the graph, the whole graph cannot be garbage collected.”
Another feature of MemLab is that it provides a “graph view of the JavaScript heap,” enabling an API for inspecting heap snapshots. This means developers can write tests that make memory assertions, such as stating that a certain object will no longer be in memory. There is also a tool for finding duplicate string instances. In one case, said the team, “we found that strings occupied 70 percent of the heap, and half of those strings had at least one duplicated instance.”
MemLab is installed via npm (Node Package Manager) or can be built from the git repository, though Windows users must use Git Bash or the build will fail. Developers can then run MemLab, passing it through scenarios defined in JavaScript files.
Browsers including Chrome, Edge and Firefox do have their own memory inspection tools, but as a dev commented on Hacker News, “it’s incredibly difficult to debug memory leak even with dev tools.”
Another strong feature of MemLab is the ability to run it in tests as part of a command-line process, meaning that if a severe leak is introduced it can be caught before an application makes it into production.