在jQuery中使用实时而不是绑定会对性能产生影响吗? [英] Is there a performance impact in using live instead of bind in jQuery?

查看:47
本文介绍了在jQuery中使用实时而不是绑定会对性能产生影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了有关livebind的一些问题,但都没有关于性能的问题.我认为标题很清楚,因此在jQuery中使用live会对性能产生影响吗?我之所以这样问,是因为使用live时每次触发事件时都必须进行查找,而我认为这可能会对性能产生负面影响.还是jQuery在做一些神奇的事情来加快这一步,例如侦听在向DOM中添加某些东西时触发的某种事件?

I found some questions regarding the live and bind, but none of them was regarding the performance. I think the title is quite clear, so is there a performance impact in using live in jQuery? Why I'm asking this is beacuse you have to do the lookup everytime the event is fired when using live and my thought is that this might impact the performance in a negative way. Or are jQuery doing some magic stuff that speed up this, like listening to some kind of event that is fired when something is added to the DOM?

推荐答案

通常,当站点上有很多(...)元素时,使用.live()/.delegate()具有更好的整体性能.需要有一个事件处理程序.

In general, it has a better overall performance to use .live() / .delegate() when you have lots of (...) elements on your site which need to have an event handler.

将50x事件处理程序绑定到50个不同的节点比将一个事件处理程序绑定到这50个元素的公共父节点上要昂贵得多(基本上是.live()的作用).

It's more expensive to bind 50x event handlers to 50 different nodes than just to bind one event handler to a common parent of these 50 elements (which basically is, what .live() does).

现在人们可能会争辩说:好极了,但这伴随着开销事件冒泡",这是绝对正确的.这就是引入.delegate()的原因. .live()始终将处理程序绑定到document.body,而该document.body显然是标记中任何子节点的父级.但是,.delegate()带有一个参数,您可以在其中指定最低公分母",这意味着您要具有事件处理程序的那些元素共享的最接近的父节点.这实际上将开销减少到了零.

Now one could argue, "well, great, but this comes with overhead event bubbling", which is absolutely correct. That's why .delegate() was introduced. .live() always binds a handler to the document.body which obviously is the parent of any childnode in your markup. .delegate() however takes an argument, where you can specify the "lowest common denominator", which means the closest parentnode that is shared by those elements you want to have an event handler. This reduces the overhead actually to zero.

我必须承认,我从来没有做过基准测试,但是使用实时绑定"才有意义.但是话又说回来,只要您将一个以上的处理程序绑定到一个元素,就有意义了.对我来说,只有一个功能而不是N的事实对我来说很方便.

I have to admit that I never benchmarked (yet) at which point it makes sense to use a "live binding". But then again, it makes sense as soon as you got more than one element to bind handlers to. Only the fact that there only is ONE function instead of N seems convenient to me.

这篇关于在jQuery中使用实时而不是绑定会对性能产生影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆