emilhem emilhem - 27 days ago 12
Javascript Question

Does Ajax (XMLHttpRequest) objects cleanup after use?

If you define a function like:

function fetchData(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readystate === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.open('GET', 'http://example.com/', true);
xhr.send();
}


Now imagine me running the
fetchData
function a lot.

So the question is, do I need/should I run
xhr = null;
after callback has executed?

I know that JavaScript has a garbage collector but does not setting
xhr
to
null
hurt?

This question is similar to XMLHttpRequest - freeing after use? but I feel that it didn't get an answer that explains that the object is in fact put in such a state where the Garbage Collection will remove it.

Answer

I highly encourage you to read entirely the mozilla documentation that you linked:

Allocate the memory you need, use the allocated memory (read, write) and release the allocated memory when it is not needed anymore. The first and second parts are explicit in all languages. The last part is explicit in low-level languages, but is mostly implicit in high-level languages like JavaScript.

Garbage collection by references:

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object. There is a limitation when it comes to cycles.

Mark-and-sweep algorithm:

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable". This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

Conclusion: If your object is not reachable from anywhere (in your case when you exit the function), it will be garbage collected. This is not something that you have to worry about in higher level languages.

Edit: Thanks Roland Starke for pointing out that you can read the specifications of how the garbage collector will handle the XMLHttpRequest here.