Comparing Memory Consumption of Delegated Event Listeners and Individual Event Listeners in Javascript
Mohamad Harith
Posted on December 25, 2021
This article assumes the reader understands what is event delegation and event bubbling.
While working on a frontend project, being the amateur programmer that I am, I initially did not understand why my HOD insisted that we handle events for long list of items by means of event delegation instead of attaching individual event listeners for each list item. After hearing his explanation and doing some readings, I came to an understanding that event delegation has several benefits in comparison to attaching individual event listeners to a long a list of items. Among the benefits are as follows:-
- Memory: More event listeners means more memory consumption as the browser has to listen to more events.
- Code maintainability: Event delegation improves code maintainability because events from multiple elements can be handled all in one place in contrary to handling them individually.
However, in order to see the benefits of event delegation in terms of memory consumption before my own eyes, I have conducted an experiment where I wrote two HTML pages that each generated list of 100k items. For one of the lists I attached individual event listeners for each li
element and and for the other list I attached a single delegated event listener on the ul
element. I then compared the memory consumption of these two pages using Firefox's task manager.
Individual Event Listeners
<body></body>
<script>
function handleClick(e) {
console.log(e.target.id);
}
var ul = document.createElement("ul");
for (var i = 0; i < 100000; i++) {
var li = document.createElement("li");
li.id = `${i}`;
li.onclick = handleClick;
li.innerHTML = `Item ${i}`;
ul.append(li);
}
document.body.append(ul);
</script>
Delegated Event Listeners
<body></body>
<script>
function handleClick(e) {
console.log(e.target.id);
}
var ul = document.createElement("ul");
ul.onclick = handleClick;
for (var i = 0; i < 100000; i++) {
var li = document.createElement("li");
li.id = `${i}`;
li.innerHTML = `Item ${i}`;
ul.append(li);
}
document.body.append(ul);
</script>
Memory Consumption
As you can see above, the memory consumption on the page that contains the list with individual event listeners was definitely higher than that of the list with delegated event listener. Therefore, it is proven that delegated event listener is more performant and should be used when listening to events from a large list of items.
Related Articles
https://betterprogramming.pub/event-delegation-in-javascript-boost-your-app-performance-5f10f25cec96#:~:text=Performance%3A%20The%20event%20delegation%20will,DOM%20will%20update%20every%20time.
https://gomakethings.com/why-is-javascript-event-delegation-better-than-attaching-events-to-each-element/
Posted on December 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.