About

Labels

slider

Navigation

Memory leaks and memory management in Javascript


Javascript is a garbage collecting language, means once the function is invoked the browser clears the memory of the function, that includes all the local variables and arguments. This clearing up of memory, in case do some malfunction will result in memory leak. This one normally increases the memory of the browsers, sounds like e-bomb.

There are several systematical as well as syntax errors that causes memory leaks in Javascript. Further closure increases the possibilities of memory leaking due to poor coding. So lets begin with it.

Before moving on read what are closure and nested functions, they creates a memory leak in the system and this could lead your whole system to failure. A web application, that are complex ones should care of using closure because they could be fail while performing some functions.

Memory flashing

Memory flashing is a normal process necessary for an application to work correctly, and a well written script will let browser do this without harming application.

Have some code:
function doIt(x){
return x+5;
};
doIt(10); // returns 15
As doIt() function invokes, x is removed from memory because there is no more use of it. As much as many times function invokes, it flashes memory every time.

Okay this one doesn't flashes memory after outer is invoked.
function first(x) {
    return function (y) {
        return x + y
    };
};
var outer = first(5);
var inner = outer(10);
console.log(inner); // logs 15
Once the first() is invoked, memory is not flashed because it stays in scope for inner function. But when inner function is invoked, memory is flashed.
P.S: above one is normal.

Memory Leak

Memory leaking have several reasons, they could be poor coding, browser bugs or any sort of plugin working in system that interrupts with working script. Older browser are nightmare in every case, even in Javascript they have quite issues collecting garbage.

Circular reference

Poor scripts are one of the factor that could be corrected by a programmer in order to clear as many memory leaks as possible. Refer this diagram as starting:


Javascript and DOM both of them have their own garbage collector when Javascript object and DOM object refers each other or points to each other creates a circular reference. Example of circular reference is right here majesty.
<HTML>
   
    <HEAD>
        <script language="javascript">
            function initpage() {
                window.setTimeout("window.location.reload()", 500, "javascript");
            }
        </script>
    </HEAD>
   
    <body onload="initpage()">
        <div class='menu' id='menu'></div>
        <script language='javascript'>
            hookup(document.getElementById('menu'));

            function hookup(element) {
                element.attachEvent("onmouseover", mouse);

                function mouse() {}
            }
        </script>
    </body>

</HTML>
Now checkout above example,  I got this from Microsoft support page. Save it as a HTML file, run it and you will notice a rapid increase in memory after each refresh in your task manager. As you can see that that hookup function have a DOM element in argument, means in scope and under it, mouse function referring back to that DOM element. This Javascript object and DOM object reference to each other creates circular reference.

Circular reference creates memory leak because Javascript and DOM garbage collector interfere with one and other and result and memory leak.

Handle big data

Consider a variable with a string or data which is quite big. If any kind of big data is in memory which is useless due to in scope of closure then it will decrease performance of system. Take an example:
function outer() {
    var bigdata = "Any big data....";
    return function inner() { // Some function
    };
}
outer(); So once, you think big data have no use then use null with the object to be garbage collect it from memory.
function outer() {
    var bigdata = "Any big data....";
    return function inner() { // Some function
    };
    bigdata=null
}

Last Words 

Once you complete coding, make sure when you test your app make sure that you take care of memory leaks in script. If something is there google it. THere are many possibilities can't be discussed in a single post like ajax call on setInterval. There are tools out there to detect memory leaks in script.

Something relevant? Comment below.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: