Member-only story
5 Common JavaScript Memory Mistakes
Tips to avoid memory leaks in your web apps
JavaScript doesn’t provide any memory management primitives. Instead, memory is managed by the JavaScript VM through a memory reclaim process. That process is known as Garbage Collection.
Since we can’t force it to run, how do we know it will work properly? What do we know about it?
- Script execution is paused during the process.
- It frees memory for unreachable resources.
- It is non-deterministic.
- It will not inspect the whole memory in one go but will run in multiple cycles.
- It is unpredictable. It will execute when necessary.
Does that mean we don’t have to worry about resources and memory allocation? Certainly not. If you aren’t careful, you might create some memory leaks.
What Is a Memory Leak?
A memory leak is an allocated piece of memory that the software is not able to reclaim.
That Javascript provides you with a garbage collection process doesn’t mean you are safe from memory leaks. In order to be eligible for garbage collection, the object must not be referenced elsewhere. If you hold references to unused resources, you will be preventing those resources from being unallocated. That is known as unintentional memory retention.
Leaking memory may result in more frequent garbage collector runs. As this process will prevent scripts from running it might slow down your web app. That will make it less snappy, which will be noticed by the user. It can even lead to your web app crashing.
How can we prevent our web app from leaking memory? We have to avoid the retention of unnecessary resources. Let’s look at the most common scenarios where this might happen.
1. Timer Listeners
Let’s look at the setInterval
timer. It is a commonly used Web API feature.
“The
setInterval()
method, offered on theWindow
andWorker
interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so…