Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery.data cause a memory leak?

Would the following piece of code create a memory leak.

According to the jQuery documentation use of the data function avoids memory leaks. It would be useful to confirm whether the following is safe.

var MyClass = function(el) {
    // Store reference of element in object.
    this.element = $(el);
};

// Store reference of object in element.
$('#something').data('obj', new MyClass('#something'));
like image 334
Lea Hayes Avatar asked Aug 16 '11 16:08

Lea Hayes


1 Answers

Obviously the code as it stands would take up extra memory as long as the DOM element is still connected to the DOM. But I'm guessing you're asking whether it would continue using extra memory after the DOM element is no longer in use.

Update: Thanks to Joey's answer (which he has since deleted), I spent some time reading up on memory leaks in javascript, and it appears my assumptions in the paragraph below are incorrect. Because DOM elements don't use pure garbage collection, a circular reference like this would normally prevent both the DOM element and the javascript object from ever being released. However, I believe the remainder of this answer is still correct.

Without a deep knowledge of how javascript engines implement garbage collection, I can't speak authoritatively on the topic. However, my general understanding of garbage collection makes me think that your code would be "safe" in the sense that after the #something element is removed from the DOM, the resulting MyClass object would only have a reference to an object that has no other connections. The graph algorithms of the garbage collector should be able to identify that the DOM element and its MyClass object are "floating in space" and unconnected to everything else.

Furthermore, jQuery goes out of its way to strip data and events that are associated with a given DOM element once it is removed from the DOM. From the documentation:

jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page.

So assuming you use jQuery consistently, you would only have a one-way reference once the object is removed from the DOM anyway, which makes it that much easier possible for the garbage collector to know it can get rid of these objects.

So as long as you don't have something else referencing the MyClass object once the DOM element is removed, you shouldn't have a memory leak.

like image 75
StriplingWarrior Avatar answered Oct 13 '22 04:10

StriplingWarrior