开发者

Is bind() faster than live() and delegate()?

My team is building a mobile website using jQuery Mobile, and as we are nearing the release date performance is becoming more of a concern. One observation I've made is that we have lots of calls to live() and delegate() throughout our code; but in fact, to my knowledge, we are only ever using these methods to attach event handlers to DOM nodes that already exist (and will always exist, in the context of our application).

Given that live() and delegate() are both intended to provide dynamic binding to nodes that may appear later on in the DOM, and considering that each of these involves handling events that have bubbled all the way up to the document root node, I wonder if we would see a performance improvement by changing these calls (where appropriate) to bind() instead.

I'm aware that I could probably test this in some way mysel开发者_如何学运维f, but I don't have a great deal of experience doing performance testing with JavaScript and I'm thinking it would probably take me longer to figure out than it would for me to simply ask the community. Has anyone tested this? Is there a measurable difference? Or would switching these live() and delegate() calls over to bind() be a waste of time?


It depends on how you use it but delegate offers the best performance (not necessarily in terms of speed only but overall) in most cases:

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/


I haven't measured anything, but live is likely to be faster than bind for larger numbers of elements, since bind needs to affect every element.

If you bind an event to 200 elements, jQuery needs to loop through all of those elements and call addEventListener on each one.
If you live an event to 200 elements, jQuery just adds a single event handler to the <body>.
However, this means that every event that bubbles up to the body must be tested against each selector that you have lived.

Therefore, the fastest option should be to delegate to the element that contains as little as possible (so that it gets fewer other events that must be tested against your selector)


I did a simple benchmark against the three. Generally speaking, Delegate is the most efficient. The exception is when the element being bound to is static and known. Even with multiple static elements, bind consistently outperformed Delegate. Bind does have more initial overhead, but Delegate has more event-time overhead.

See my results at .live() vs .bind()


bind is used to bind he event directly on the element. So the event will be attached only if the element exists where as live and delegate are used for dynamic elements also. It depends on your use but live and delegate provide better performance than bind

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜