Memory Leaks

Table of contents

No heading

No headings in the article.

Computers do a variety of things, you can play games, see movies, and converse with your loved ones and folks you hate (Twitter). In our case, we write programs that shape the human experience and at the heart of all this is the simple idea of an input being processed to give an output, You click on a video file and it produces an audio-visual output, this process takes a variety of resources to complete and at the heart of there resources are Time and Space.

Time is the duration it takes for an instruction to run to completion, Space is the amount of memory needed for the said instruction to run to completion.
When building web applications, surprise surprise, you are writing code and that code needs time and memory to compile and render. Programming takes Murphey's law to the very extreme, if something can go wrong then it will go wrong. This is no exception, roll credits, Memory leaks.

Memory leaks, remember when I said memory is needed for instructions to run to completion? so a memory leak happens when that assigned memory cannot be reclaimed. Wikipedia says, paraphrasing here, incorrectly managing memory in a way that memory that is no longer needed is not released. Let's take a small dive into how javascript or any programming language more or less handles memory in the memory lifecycle.

Memory Lifecycle.
This is a three-step process, allocation, usage and release.
1. Memory Allocation: memory is allocated to the program by the operating system.
2. Memory Usage: Here the memory is used for whatever instructions are required for the program to be deemed complete.
3. Memory Release: After the program is completed, the memory resource allocated is released, for javascript programs, this is handled by the garbage collector.

Quickly how does garbage collector work? Reachability. Reachability? Reachability.
if your code is reachable, meaning something is referencing it, or it is accessible or usable, then it is sure to have memory allocated to it. The job of the garbage collector is to remove the values that have become unreachable

How are memory leaks then created?
Well, several ways really,

  1. Closures: closures are functions that reference their lexical environment, this function simply put has access to the outer function scope.
    Variables in a function get cleaned up when the call is complete or executed but because the references of the outer scoped variables remain in memory, unused I might add, even after the execution of the function is complete is one source of memory leaks.
function test() {
    const array = []
    return function addValue(value){
        array.push(value)
    }
}

const variable = test() //get the add value function

In the code box above, the array variable is never returned and cannot be reached by the garbage collector and can be a source of memory leaks.
The simple solution to this particular issue is to ensure that the variable in the outer scope is returned or is used.

  1. Timers: Ah, yes, the good old, setInterval and setTimeout, setInterval executes repeatedly for the set interval and setTimeout runs when the set time runs out, these two can be a source of memory leaks, when they are forgotten and not updated.

     function doSomething() {
         const value = []
         return function(){
             value.push('something')
         }
     }
    
     setInterval(doSomething(), 2000);
    

    In the above example, the function doSomething returns a function that appends 'something' to the outer scoped value array, and since it is called using the setInterval, and as we explained earlier about the mechanics of the setInterval method, the function, doSomething, it runs periodically and this results in a large size for the values array.

    To resolve this issue, it is said to have a reference inside the calls to setInterval and setTimeout, and then make calls to make sure they are cleared.

     const timer = setInterval(doSomething(), 2000);
     // this is done after say an action occurs, user performs an action, clicks on a button or say an api call is successful or failed etc.
     clearInterval(timer)
    
  2. Global Variables: referencing an undeclared variable creates a new variable inside the javascript global object, now the global object exists on the global scope, it basically hosts variables that should be available everywhere, now the problem with referencing an undeclared variable is that the global object becomes its 'root'(one of the inner workings of javascript) and references directly tied to the root are always active and the garbage collector cannot clear it, which results into a memory leak.
    A solution is to limit the use of global variables, ensure variables are function scoped, also adding 'use strict' enables a stricter mode for javascript or just use Typescript, just saying.

Memory leaks causes all sorts of problems, before we move there, some of you might be thinking in the lines of "well, this should be a minor issue", let's use an example of a house, newly built, properly furnished and looks amazing, now take for example, the gate breaks down, no one pays any attention, and then one of the windows is broken by some kid playing football, well that's also minor, another day the guy washing his car has dirt all over the painted walls and now the walls don't look as good as they used to, another day one of the buttons of the elevator stops working, that's also minor, well you see where I am headed with this. In no time, the once beautiful house now looks like a dump and no one wants to live there. The same concept applies to bugs when left unattended, not just memory leaks.
Now that is established, some of the issues caused by memory leaks include:

  • Crashing the system.

  • Random refresh of a page.

  • Affecting the project's performance by reducing the amount of available memory

  • Overloading the database with an absurd number of queries and requests, which could also lead to crashing.

Detection of leaks.
Using the developer tools of your preferred browser, navigate to the memory tab and take a heap snapshot and make a comparison between the duration before you made an action and after you performed the said action.

In conclusion, we have learnt what memory leaks are, some of the sources of memory leaks, how they can be corrected and what the effects of these memory leaks have on your system.

I hope you were able to pick something from this article, until the next one.
Cheers!
ps, I had written a considerable amount on this topic and accidentally clicked on one of my bookmarks, came back and nothing was saved, So I am a little pissed.