Akash Kava
Akash Kava

Reputation: 39956

Does following code cause memory leak in JavaScript?

Following is part of very big logic, function track is just for simplification. Track loads object from database and stores in cache.

var cache = [];

function newObject(a){
   var b = {};
   b.tracker = a;
   cache.push(b);
}

var t = {};

track(t);
track(t);
track(t);
track(t);

...

cache.length = 0;

track(t);
track(t);
track(t);
track(t);

....
cache.length = 0;

After clearing cache, does it cause memory leak because b.tracker is holding reference to t? For clarification, tracker t does not store any reference to any object created.

Do I need following method?

for(var i=0;i<cache.length;i++){
    cache[i].tracker = null;
}
cache.length = 0;

Or JavaScript engine is smart enough to remove all instance of b because no body references b anymore?

Upvotes: 0

Views: 106

Answers (2)

flavian
flavian

Reputation: 28511

When a variable goes out of scope, it gets garbage collected. Now to remove that cache, you would have three ways:

delete cache; // which is not possible because it's defined with var.
cache = [];
cache.length = 0;

For the last one, cache.length = 0; I noticed the effect is the desired one. It results in n delete operations of the type delete cache[i]. As soon as the delete operation happens, the value held in cache[i] is de-referenced, goes out of scope, and the garbage collector kicks in.

So yes, the JavaScript engine is smart enough to do that. I tested with 4 sets of profiling tools(Chrome, Safari, Firefox and Opera). I lack the extreme patience required to own a Windows machine, so I couldn't test in Internet Explorer.

Update

According to @Renan the above works just as well in Internet Explorer, so cache.length = 0 is definitely the way to go.

Upvotes: 3

Geeky Guy
Geeky Guy

Reputation: 9379

Javascript should reclaim the memory occupied by your t if that's all you're doing. You don't have to set an array item to null if you're setting the array's length to zero.

Upvotes: 2

Related Questions