DEV Community

Cover image for Thought Process: Avoiding Memory Leak in Code
Oludamola
Oludamola

Posted on

Thought Process: Avoiding Memory Leak in Code

The first time I heard of Memory Leak was in a job interview. I was asked to write code that counts down from a particular number, and by default, I started writing something around using setTimeout.

Instantly, the interviewer called my attention, explaining why I should use setInterval instead (setInterval maintains a more consistent interval). Out of my usual character, I didn’t panic about doing things wrongly. I listened to him as he explained how using setInterval and clearInterval was a cleaner way to handle such an operation - “to avoid memory leak.”

Once I was off the call, I researched ‘Memory Leak.’ I took in as much info as I could about it, and till now, I stop to read whenever I see memory leak-related content, even though I now have a better understanding. By the way, I got the job (apparently, missing one question doesn’t always spell doom in an interview).

Anyway, let’s look at what a memory leak is, the scenarios that cause it, and what that interview encounter did for me.

What is a Memory Leak?

A memory leak is a situation where memory allocated to the running of an application is not freed up during garbage collection because it’s still being tied by the object initially using it. Thanks to this, the program ends up using more memory than needed.

As you are probably guessing, this leads to a domino effect of poor performance, which results in bad user experiences, unnecessary costs, etc. While programming languages like JavaScript can do automatic memory management, there are times when explicit cleanup is still required to prevent memory leaks.

So, using JavaScript, let’s look at some causes of memory leaks.

Causes (and fixes) of Memory Leak in JavaScript.

This piece uses JavaScript as a case study, but memory leaks happen in other programming languages, too, right? So, you should find out about them yourself. But for my JavaScript folks, some cases may lead to memory leaks.

Wayward global variables.
If you’re using React majorly, this might be less of an issue. But if you’re writing pure JavaScript and erroneously declare a variable that finds its way to a global context, you could be in for a long time. This is because global variables maintain references that prevent other objects from being garbage-collected.

In the code below, assigning value to a variable name without properly using var, const, or let makes it available globally. In this example, the leak is only a string; in other situations, it could be a variable that takes large memory and costs your system.

Image description

Event listeners
Again, if you’re building with pure JavaScript and using event listeners, not cleaning those up could cost you memory. So, don’t forget to removeEventListener when you’re done.

Image description

SetInterval and SetTimeout
When you’re doing stuff related to time, countdowns, etc., you’ll probably need to use setInterval or setTimeout per preference, even if you’re a react dev. Now, upon usage, if you don’t manually clear your interval, some resources - specifically, the operation you’re performing in the interval - will continue to take up memory. So, cleaning up after yourself is essential.

Image description

More Causes

Now, some other specific cases can cause memory leaks. Out of DOM references, anonymous functions that capture variables from parent scopes, and improper cache management. But all these could be easily detected if you’re writing JavaScript in strict mode - highlights where you’re not cleaning up properly.

The bottom line is that you should be out of the woods and not turn your app into a memory-sucking animal when you do the following.

  • Use const or let when declaring variables; don’t make the rookie mistake of declaring variables without these.
  • Clean up when you using timers and event listeners.
  • Be careful with caches.

React can reduce the risks of memory leaks but can’t eliminate them; it can still leak memory if cleanup functions aren't properly implemented in useEffect hooks. So, due diligence is key.

The Importance of Learning About Memory Leak

The most important lesson I took home from that interview wasn’t about the concept of memory leak itself. It also wasn’t about the fact that missing one question during an interview doesn’t spell doom - you could still get the job despite messing up - or not.

That scenario taught me the importance of being conscious of the code I write - actively thinking through the process and why I make the decisions on every line of code. Why am I using if/else statements instead of the switch statements? Why am I using slice instead of splice when returning an extracted subset of an array?

Of course, I didn’t suddenly go from zero to a hundred regarding my thought process when coding. In fact, I'm still far from 100. Since I started the job, the senior - who interviewed me - always takes the time to review my code, question my subpar decisions, and ask me to redo them. Funnily, I don’t find this annoying. I appreciate him suggesting better approaches when I write something that could have been written better. I might not see the instant impact of all his reviews in my capabilities, but I know it’s compounding. His input is refining my thought process.

I’m now more particular about my thought process while building stuff. Hence, I decided to start writing this series, which explores the thought process behind specific implementations I do. I want to lay bare how I think about solving problems with code, and hopefully, someone might have a better approach I can learn from.

Please always comment when you have a better approach to a problem.

Top comments (0)