Why is event binding in jQuery much slower than native javascript?

I exposed a bit of JSPerf to test the performance of event bindings in Javascript. I knew native javascript would be the fastest, but what really surprises me is how the jQuery error edge is slower. And also the big difference between running jQuery binding for javascript object and jQuery object.

The code I used is below. JSPerf for this code is here .

var div = document.createElement('DIV');
var handler = function(){};
var jq_div = $('div');

// #1 - native javascript test code
div.addEventListener('click', handler);

// #2 - jquery event binding on javascript object
$(div).on('click', handler);

// #3 - jquery event binding on jquery object
jq_div.on('click', handler);

      

Can someone explain to me why this is a difference, mostly between cases # 2 and # 3. I didn't expect much difference. And also if there is any way to improve the execution of jquery event binding?

Thanks for your efforts in advance.

+3


source to share


1 answer


Can someone explain to me why these differences

jQuery has to do everything that internal linking does, plus the huge amount of overhead that jQuery uses for its internal event system.

mostly between cases # 2 and # 3



Yours is var jq_div = $('div');

wrong. It selects all elements div

on the page and associates events with all of them; you wanted var jq_div = $(div);

or var jq_div = $('<div>');

.

Is there a way to make jquery event binding work better?

Not. And absolutely unnecessary. The binding (as opposed to "firing") event happens almost never in the application - this is a very rare task. And as your jsperf test confirms, it still happens thousands of times per second, which is fast enough. If you really need to bind events to a very large number of items at once, use event delegation.

+2


source







All Articles