添加过多的事件侦听器是否会影响性能? [英] Does adding too many event listeners affect performance?

查看:45
本文介绍了添加过多的事件侦听器是否会影响性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 javascript (jQuery) 事件/侦听器的一般性问题.在不出现性能问题的情况下,点击监听器的数量是否有限制?

I have a general question about javascript (jQuery) events/listeners. Is there any limit for the number of click listener without getting performance problems?

推荐答案

在性能方面,事件绑定到的元素数量是您会发现任何问题的地方.

In terms of performance, the number of elements the event is bound to is where you'd see any issues.

这是一个jsperf 测试.您会发现绑定到许多元素要慢得多,即使在每种情况下只绑定一个事件.

Here is a jsperf test. You'll see that binding to many elements is much slower, even though only one event is being bound in each case.

jsperf 中的第三个测试展示了如何将事件绑定到父元素并使用委托来侦听所需的元素.(在这种情况下 .many)

The 3rd test in the jsperf shows how you'd bind the event to a parent element and use delegation to listen for the elements you want. (In this case .many)

n.b.测试表明,第三个选项是最快的,但这是因为它针对的是带有 id 而不是类的元素.

n.b. The test shows that the 3rd option is the fastest, but that's because it's targeting the element with an id and not a class.

更新:这是另一个性能测试显示绑定到 id 的 3 个事件与使用 class

Update: Here's another perf test showing 3 events bound to an id vs one event bound using a class

这篇关于添加过多的事件侦听器是否会影响性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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