How can I prevent memory leaks when removing images in the DOM?

I have used 3 different types of approaches…

First. Did add a set of images and left the garbage collection to browser.
enter image description here

It definitely garbage collected, but after a while, making sure that there exists no need for the images which have been created.

Second. Used a data:URI patterns for the src for images.

var s = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

for (var i = 0; i < 100; i++){
    var img = document.createElement("img");
    img.src = s;
document.getElementById("myList1").appendChild(img);
setTimeout(function(){img = null;}, 1000);
}

enter image description here

This looked similar, though a bit better for me as I was watching in front of my browser and observed a lesser memory was used, and garbage collection was almost the same as above.

Third. Did garbage collection in code.

var s = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

for (var i = 0; i < 100; i++){
    var img = document.createElement("img");
    img.src = "https://stackoverflow.com/questions/13859041/dot.png";  // or the other, both mean the same here.
    img.src = s;
document.getElementById("myList1").appendChild(img);
setTimeout(function(){img = null;}, 1000);
}

enter image description here

In this short time of testing, I believed that the last approach worked better, as it was almost freeing the space up immediately without waiting to see if there was any need for the referenced images further.

All in all, You better use garbage collection by yourself, when you absolutely feel like something must be freed off.

Leave a Comment