Is a delegate the fastest way to bind?

Can anyone explain why the delegate looks faster than binding aliases or on ().

This is a test case:

jsPerf

$('p').on('click',$.noop); //80% slower $('p').click($.noop); //84% slower $(document).delegate("p", "click",$.noop); //fastest 

Checking the jquery source, it seems, before binding any event, checking the jquery for delegates.

Is this the right statement or something else?

+6
source share
3 answers

The mistake you made was to think that there is only one p element.

I added another test only with console.log($('p').length); , and he showed that 7 p was visible from the test, whose visibility was obviously not limited to the HTML that you created in the preparation code.

This means that the first two functions had to make 7 more bindings.

+6
source

Both delegate() and bind() just call on() . Here is an excerpt from jQuery 1.9.0 source:

 bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, 

So, on() should be a little faster than the other two functions, as this is another function call. The actual call to the handler must be identical no matter how it was connected.

But make sure you compare apples to apples. If you give the selector argument for delegate or bind , the call to the handler will be slower because it needs to check if the target selector satisfies.

The reason your test result is because

 $("p").on('click',$.noop); 

equivalent to something like:

 $("p").each(function() { $(this).on('click', $.noop); }); 

He must find all the relevant elements and associate a handler with them. The delegate() call should only bind the handler to one element (document); instead of finding all the elements during the binding, at the time the event occurs, it does something like:

 if ($(event.target).is("p")) { ... } 

Using on() , equivalent to delegate() , would be:

 $(document).on('click', 'p', $.noop); 

When you delegate a large element of type document , you call the internal handler every time you click anywhere in the document, wasting time, checking to see if you exceed p . That's why you should try to limit the scope of the element used in the delegate to the smallest static element that contains all the dynamic elements that you want to delegate.

+5
source

the delegate only works faster because you do not need to search for any elements, if you use a selector instead of the delegate of the elements will be the slowest

 <div> <p>test</p> </div> $('p').on('click',$.noop); $('p').click($.noop); $('div').delegate("p", "click",$.noop); 

http://jsperf.com/test-on-click-delegate/3

+5
source

All Articles