function fetchXmlDoc(uri) {
var xhr = new XMLHttpRequest();
var async = false;
xhr.open("GET", uri, async);
xhr.send();
return xhr.responseXML;
}
Basically, when I call this function, will the xhr
object get garbage-collected, or will it stick around forever because the caller is holding on to xhr.responseXML
? If it's the latter, would this solve it?
function fetchXmlDoc2(uri) {
var xhr = new XMLHttpRequest();
var async = false;
xhr.open("GET", uri, async);
xhr.send();
var xml = xhr.responseXML;
return xml;
}
Despite all my years of JS, the whole memory-management thing still manages to confuse me...
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.
No, Garbage collection does not guarantee that a program will not run out of memory. The purpose of garbage collection (GC) is to identify and discard objects that are no longer needed by a Java program, so that their resources can be reclaimed and reused.
An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.
JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.
The responseXML property of the xhr object is a reference to the actual data object (just as you've implicitly assumed in the second piece of code: you're not copying the data, you're copying the reference).
So the xhr
object will eventually get garbage collected. There is only one reference to it: right here in this function where it's created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With