javascript - Why is my vanilla JS code slower than jQuery equivalent and how to profile it? -



javascript - Why is my vanilla JS code slower than jQuery equivalent and how to profile it? -

after using heavily jquery, have found out, basic operations much faster in vanilla js (duh!) , hence improve write in pure js using heavyweight jquery everything.

but vanilla js slower , slower lot equivalent in jquery. right now, have scenario. jquery's delegated .on() function against simple version. code much simpler , doing "less things" expecting result in favor of vanilla js. using jsperf see code 60%+ slower. code illustration below.

can explain why? can show me practical way how profile code , find reply myself next time ? can see bottleneck or inefficience ? have tried using built-in profilers both in chrome , firefox didn't help me much, showing function phone call takes 1ms of time , nil useful. there improve tools or using them wrong ?

my illustration scenario 3 nested divs. hear event @ top div delegate handler attached catches events on nested divs. fire click event on lowest div , in jsperf measure time took handle event.

// simple function firing "click" event function clickit(node) { var event = document.createevent("mouseevents"); event.initevent('click', false, true); event.synthetic = true; node.dispatchevent(event, true); } // simple implementation of jquery's delegated .on() function var f = { hasclass:function(el, class_name) { homecoming el.classname.split(" ").indexof(class_name) > -1; }, live:function(el, target, event_type, fn){ if ('class' in target) { var live_handler = function(event){ var target_el = event.target; while (target_el != el) { if (f.hasclass(target_el, target.class)) homecoming fn.call(target, event); target_el = target_el.parentnode; } event.stoppropagation(); }; } else { var live_handler = fn; } el.addeventlistener(event_type, live_handler, true); } }; </script> <div id="test1"><div id="test2" class="target"><div id="test2_2"></div></div></div> <div id="jq_test1"><div id="jq_test2" class="target"><div id="jq_test2_2"></div></div></div> <!-- attaching event handlers --> <script> var test1 = document.getelementbyid('test1'); var jq_test2_2 = document.getelementbyid('jq_test2_2'); f.live(test1, {class:'target'}, 'click', function(event){}); $('#jq_test1').on('click', '.target', function(event){}); </script>

jsperf available testing here.

javascript jquery performance profiling

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -