I have some code that adds a mouseover event handler to svg circles to display tooltips. Should I remove/unbind these handlers when I remove the circle elements? I do not know if these handlers are attached to the svg object and I am afraid it may lead to shadow dom or memory leaks. See code below :
circles.enter().append("svg:circle")
.on("mouseenter", function(d) {
// show tooltip
});
circles.exit()
.on("mouseenter", null) // necessary?
.remove();
I think you have your answer already but I was interested in how you show that this is true, at least in latest Chrome.
This is the section of the D3 code that removes DOM nodes:
function remove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
export default function() {
return this.each(remove);
}
So as you can see it's depending on the browser to do cleanup of any associated listeners.
I created a simple stress test of adding/removing lots of circle nodes with D3:
var circles = svg.selectAll("circle")
.data(data, function(d) { return d.id; } );
circles.exit().remove();
circles.enter().append("circle")
.attr("id", function(d) { return d.id; })
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr( { r: 5, fill: 'blue' })
.on("mouseenter", function(d) { console.log('mouse enter') });
Live version here: http://bl.ocks.org/explunit/6413685
You will notice that the DOM node garbage collection counts correspond with the event listener garbage collection counts. In fact, you can't really tell them apart in the below screenshot since the lines are superimposed:
Note that for Internet Explorer, things are a little more complicated.
See also this article for more tips on tracking memory usage in Chrome tools.
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