Consider this multi-level nested JavaScript object.
function foo() {
var channels = {
2: {
name: "station 1",
description: "station1",
img: ["img1-a", "img1-b", "img1-c"]
},
3: {
name: "station 2",
description: "station2",
img: ["img2-a", "img2-b", "img2-c"]
},
4: {
name: "station 3",
description: "station3",
img: ["img3-a", "img3-b", "img3-c"]
},
};
console.log(channels);
};
....
// calling foo.
foo();
After the function foo() returns, will all the nested objects (i.e. the individual channel objects, strings, the array img, and the strings in img array, all be automatically garbage collected ?
Or, do I need to explicitly iterate through and "delete" each object?
-
2There is no reference to any of those objects/arrays anymore, so they will be garbage collected eventually.Felix Kling– Felix Kling2012年03月15日 21:57:03 +00:00Commented Mar 15, 2012 at 21:57
-
See stackoverflow.com/questions/864516/…j08691– j086912012年03月15日 21:57:29 +00:00Commented Mar 15, 2012 at 21:57
-
@j08691 thanks for providing a great reference.Karthik– Karthik2012年03月16日 06:37:40 +00:00Commented Mar 16, 2012 at 6:37
4 Answers 4
Depends on what happens in console.log. Certainly in Chrome, a reference to the channels object is kept in the console, so channels cannot be GC'd.
When you remove console.log, the full channel object will properly be GC'd, because there are no other references to it.
1 Comment
They're eligible for GC as long as nothing else is referencing them.
Comments
They should be, yes, because there is no more reference to that channels object nor the closure that contains it.
GC is mostly dependent on the browser that implements it, though, so there's no guarantee it'll actually be done. deleteing each element is overkill, though.
1 Comment
Javascript has its own garbage collector implemented by the browser's engine (v8 or whatever). You don't have to deallocate references. Once the root goes out of scope, they will all be eligible for gc.