Er. Mohit Agrawal
Er. Mohit Agrawal

Reputation: 2276

Memory leak in nodejs in simple function calling

Edited Question

I was trying to understand why there is memory leak in simple function call. why node does not release memory as local scope is ended.

Thanks in advance

function somefunction()
{
    var n = 20000;
    var x  ={};
    for(var i=0; i<n; i++){
        x['some'+i] = {"abc" : ("abc@yxy.com"+i)};
    }

}

// Memory Leak
var init = process.memoryUsage();
somefunction();
var end = process.memoryUsage();
console.log("memory consumed 2nd Call : "+((end.rss-init.rss)/1024)+" KB");

Upvotes: 0

Views: 279

Answers (2)

Trott
Trott

Reputation: 70163

PREVIOUS ANSWER before the question was edited to correct a code error:

The results are invalid because this code doesn't invoke the function:

(function(){
    somefunction();
});

The anonymous function is declared but not invoked. So it does not use much in the way of resources.

You need to invoke the function:

(function(){
    somefunction();
}());

Upvotes: 1

Manish Trivedi
Manish Trivedi

Reputation: 3559

@Mohit, Both strategy taking same memory consumption. Run each code separately and check by yourself.

EDIT: Wait for gc. When gc will call then memory should be free. Try to call gc explicitly then check it.

Upvotes: 0

Related Questions