添加太多的事件监听器会影响性能吗? [英] Does adding too many event listeners affect performance?

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

问题描述

我有一个关于javascript(jQuery)事件/监听器的一般问题。
在没有获得性能问题的情况下,点击监听器的数量有限吗?

解决方案

在性能方面,事件绑定的元素数是您会看到任何问题的地方。



这是一个 jsperf测试。你会看到绑定到许多元素的速度要慢得多,即使在每种情况下只绑定一个事件。



jsperf中的第三个测试显示了 d将事件绑定到父元素,并使用委托来监听所需的元素。 (在这种情况下 .many



n.b。测试显示,第三个选项是最快的,但这是因为它的目标元素是 id 而不是类。



更新:这是另一个 perf测试,显示绑定到 id vs一个事件绑定使用


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.

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.

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. 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.

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

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

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