Speaker: @stuartrunyan
Venue: San Diego JS
Date: Decemeber 2nd
- Clean Room
- Determining If You Have a Memory Leak
- Discovering What is Causing the Leak
- Fixing Your Leak
To start you will want to use a browser with a good set of developer tools, à la Chrome.
Setting up an Environment to Test In
Before we start let's setup a Clean Room where we can ensure we won't have external sources, i.e. plugins, extensions, etc..., effecting our diagnosis results. We will do this by creating a seperate Chrome user profile. In this profile we will ensure there are no extensions running. Once you have switched to this account open the Chrome Menu > More Tools > Task Manager
you will most likely see your extension processes still running. Close chrome and reopen to kill these.
Using the Timeline
After loading your application open your developer tools, check memory and start recording. Then you'll need to go through the screenflow for the actions/events you think might be causing memory leaks. Once you've completed your actions/events, run the browser Garbage Collection. Stop the the timeline recording and inspect the memory usage graph to see if your memory usage did not return to the initial application usage. If you see that the memory footprint has increased then you my friend have a memory leak.
Let's figure out what's causing it!
Using the 3 snapshot technique
To summarize what we are going to do;
- Take a initial application Heap snapshot before you do any events.
- Replay the actions/events previously done during our diagnosis. Take another Heap snapshot.
- Repeat the actions/events again. Take another Heap snapshot.
- Compare the diffs between snapshots.
The Hard Part
Skip past the internals; (string), (array), (system), (closure), etc... and look for object names you know and are increasing in retained size. Since your objects are instances of the primitives, solving their retained size will reduce the primitives as well.
Naming your functions will come in handy when trying to identify what in your code is retaining a reference to these objects. Name ALL the functions!!!
Common leaks to watch out for:
- Detatched DOM Elements
- Circular references with closures
- Variable references
- Detached DOM elements
- Shared memory spaces between tabs
- distance
- retained size