Home

Noppanit

22 Nov 2014

Event delegation in JavaScript is fast but how fast?

People say always use event delegation for adding event because it’s faster. But how fast exactly? I really want to create a test case for this, but I couldn’t figure out how to run Benchmark.js in browser. So, I thought we could just use Chrome Developer Tool to achieve this.

What are we measuring?

As I said in the beginning, we want to know how fast event delegation is compared to direct binding that most people do. For example, I’ve always seen people do this

$('#ul li').on('click', function() {
  // doing something amazing.
});

What is actually doing is, jQuery will add the event to each of the li in the DOM. If you have 3-4 lis, then I don’t think it’s going to make a big difference. However, if you have a thousand lis, you will see some difference. I’ll show you by using Chrome Developer Tool.

What do we need?

We need some basic HTML

It’s going to be something like this

<ul id="parent">
  <li></li>
  // 999 more <li>
</ul>

Then we will have JavaScript like this

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $('#parent li').on('click', function() {
        console.log('you clicked me!');
    });

</script>

If you open your html page on Chrome you should see something like this.

If you go down to where JavaScript is executed You will see it takes around 37ms to execute the snippet.

Now change your snippet to be event delegation

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $('#parent').on('click', 'li', function() {
        console.log('you clicked me!');
    });

</script>

And refresh the page you should see something like this.

Now it will only take 2ms to execute the snippet. It’s because the event is added to one element not 1000 of them.

This is just an easy example that you can do it yourself to improve your performance.

Til next time,
noppanit at 00:00

scribble