Gordon Matshwane, Jonathan Mayunga, Denvor Naidoo, Collins Matentji, and Kelvin Sakoane
24 June 2021
As any developer would know, when an object/variable/program is created, memory is automatically allocated to it and removed when it’s no longer needed. This is usually done through garbage collection.
Despite having a garbage collector, we can’t always rely on it to release allocated memory due to issues called “memory leaks”.
Memory leaks can occur over a slow period of time and can be the fault of developers. Think of it as a pipe leak. When they occur they flood the OS and make an application slow or shut it down. This generally won’t sit well with your users and could lead to a decrease in user experience.
Here are a few examples of memory leak scenarios developers might cause:
An event listener is a procedure in JS that waits for an event to occur. A simple example of an event is a user clicking the mouse or pressing a key on the keyboard.
While it’s convenient to add an event listener to perform essential actions, we sometimes forget to remove it. This leads to the same code running twice, which slows your application. Always remember to remove your event listeners.
Timeout and Intervals
We mostly use set timeout and intervals depending on which business logic we are trying to implement. However, we might forget to clear them afterwards. If we add a set interval that runs a code every two minutes and doesn’t clear the interval after leaving that page, the latter will run an unnecessary code every two minutes. This might result in errors or a waste of memory.
Subscriptions/Background Services/Third-Party Libraries
The use of external libraries such Redux, RXJS, Mobx, etc. can expose your API subscription if you don’t dispose of them after use. Some memory leaks occur when we don’t have control over the code behind the libraries we pull into our application. Use an extra tool to detect if your app has any leaks.
Global/Out of Scope Variable
Sometimes we create global variables that we only use once inside a single function, thus allocating memories to variables on global scope instead of block scope.
How to avoid memory leaks
There are a few approaches you can follow to avoid memory leaks, namely:
- Use the clear method/function to clear timeouts and intervals;
- Remove an event after or when the element or page is destroyed;
- Unsubscribe or kill background service when no longer needed;
- Use memory leak tools;
- Manually trigger garbage collector;
- Scope your variables nicely;
- Make use of peer programming, two pairs of eyes are better than one;
- Enable code review within your team, maybe someone will spot something you missed.