Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this JavaScript code garbage-collect the way I expect?

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...

like image 687
Domenic Avatar asked Apr 01 '11 20:04

Domenic


People also ask

Does JavaScript garbage collect?

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.

Is garbage collection guaranteed to run?

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.

How can you make sure an object is garbage collected?

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.

What is garbage value in JavaScript?

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.


1 Answers

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.

like image 66
jmbucknall Avatar answered Sep 20 '22 10:09

jmbucknall