0

Two basic questions I'm having trouble finding answers to are as follows:

1) The performance of binding a click function vs. triggering it via onclick="doingness()", as in:

$("#id").find('a').on('click',function(){
    $(this).doingness();
});

versus:

<div id="id"><a onlick="doingness()"></a></div>

function doingness(){
    $('#id').do();
}

It seems to me that the second one might perform best since the binding does not need to take place until the user actually clicks, so the script doesn't have to search thorugh the entire DOM to find an id and bind something to it.. is that right?

Next, I've heard that using these (whatever this is called) are very costly:

$('body').on('click', '#id', function(){
    $(this).do();
});

Of course, I'm using a couple of these with dynamically loaded content so that the functions are kept alive. I'm guessing the performance hit mostly has to do with the whole function needing to be kept in memory and probably is getting reaccessed over and over to check if it should fire off again or not. Instead of this kind of code, I recently realized that I can also just add an onclick="doingness()" in the html instead, and my question is would this help performance?

user2777052
  • 157
  • 3
  • 11

1 Answers1

1

Comparing approach 1 with approach 2, the inline 'onclick' will be faster in the sense that the DOM does not need to be traversed to search for the right node (first search on id, then on the a-tag inside the element with the id). But to be honest, I think the extra performance (which really isn't that much/important unless maybe you are writing high-performance games or such) does not outweigh the improvement in code separation the first approach offers.

Your last block of code, in my opinion, is something you should avoid using. This form of the on-method, with the selector parameter, should (imo) be used when the event needs to be handled across a range of elements (e.g. capturing the click-event on every td in a large table). In this case, it's a big performance improvement, since you will only need one event handler instead of possibly hundreds or thousands. However, you are doing it with an id-selector, so you are using it for only one element. I understand the added bonus that it will work if the element is dynamically inserted, but instead you should wait with binding the event till after the element is inserted, and go for the regular way of capturing the event.

The onclick approach would work as well in this case, and I think it would improve performance, but again, it's not worth it because you sacrifice on code separation.

Hans Roerdinkholder
  • 3,000
  • 1
  • 20
  • 30