Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM event-listeners garbage collection

If an event listener is attached to every cell in a particular column of a table, and then every row is removed from the table, to avoid memory leaks is it necessary for the developer to remove the event-listeners before the rows are deleted, or do the browsers clean things up?

Edit: the article that Michael suggested says event delegation performs better than binding the listener directly to every cell in the table, but I am not sure if it is better from a garbage-collection perspective or just performs better. Please comment. From the article:

        $('table').on('click', 'td', function () {

            $(this).toggleClass('active');

        });

is said to be superior to:

        $('table td').on('click', function () {

            $(this).toggleClass('active');

        });

Edit2: and the jQuery documentation of .on() and event delegation also focuses on performance, but the question of what happens from a garbage-collection perspective when rows are repeatedly deleted en masse from a large table, and the cell-click is being listened to by the delegated mechanism, remains.

like image 839
Tim Avatar asked Nov 26 '22 09:11

Tim


1 Answers

I don't know exactly but i think browser(JavaScript engine) is responsible for Garbage-Collection.

and as i know this mechanism is automatic in new generation browsers

so, flow will be like this,

1. you create cells
2. you attach listeners
3. memory allocated
4. you remove cells
5. listeners becomes dangling
6. Garbage collector clears it
7. you are happy

also there are some mechanism provide to clear it explicitly, search SO for that and there will be many questions related to that

But again i am not sure ! so wait for experts to come up with solid answer

like image 92
Saurabh Bayani Avatar answered Dec 04 '22 10:12

Saurabh Bayani