0

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?

2
  • Not the downvoter, but I can only assume you're getting downvotes because you haven't indicated if you've even tested the code yet or not to see if it causes memory leaks. You're effectively saying, "Here's some code, test it for me." Commented May 6, 2013 at 12:25
  • Well there is no way to test this, I have created 1000s of objects but objects are of hardly any size to see any noticeable difference in memory management of chrome. Commented May 6, 2013 at 12:26

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It works just as well in IE 9+. I loath any and all who use older versions (it's already in 10 FFS), though I have a hunch that it would work in IE8 as well.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.