javascript 添加过多的事件侦听器是否会影响性能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28627606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does adding too many event listeners affect performance?
提问by Bernhard Pointner
I have a general question about javascript (jQuery) events/listeners. Is there any limit for the number of click listener without getting performance problems?
我有一个关于 javascript (jQuery) 事件/侦听器的一般性问题。在不出现性能问题的情况下,单击侦听器的数量是否有任何限制?
采纳答案by atmd
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.
这是一个jsperf 测试。您会看到绑定到许多元素要慢得多,即使在每种情况下只绑定一个事件。
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
)
jsperf 中的第三个测试显示了如何将事件绑定到父元素并使用委托来侦听所需的元素。(在这种情况下.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.
nb 测试表明第三个选项是最快的,但那是因为它针对的是带有 anid
而不是 class的元素。
Update: Here's another perf testshowing 3 events bound to an id
vs one event bound using a class
更新:这是另一个性能测试,显示 3 个事件绑定到一个id
使用一个绑定的事件class