简体   繁体   English

一个事件监听器循环元素VS单个元素上的事件监听器?

[英]One event listener looping elements VS event listener on individual elements?

Is it more performant to have one event listener looping elements at document level than having multiple event listeners on individual elements?在文档级别使用一个事件监听器循环元素是否比在单个元素上使用多个事件监听器更高效?

For example:例如:

const elements = []

const logic = (e) => { /*any logic*/ }

// event listener on individual elements
elements.forEach((el) => el.addEventListener('click', logic))

// one event listener looping elements
document.addEventListener('click', (e) => {
  elements.forEach((el) => {
    if (e.target.isEqualNode(el)) logic(el)
  })
})

Also, does anybody have done any valid measurement to prove that having one listener looping elements is more efficient than adding event listeners to each individual elements?另外,有没有人做过任何有效的测量来证明让一个侦听器循环元素比向每个单独的元素添加事件侦听器更有效?

I've read more on this and I think using multiple addEventListener has no affect on the performance whatsoever.我已经阅读了更多关于此的内容,我认为使用多个 addEventListener 对性能没有任何影响。

In conclusion, the only performance issue someone might encounter is by using anonymous function instead of static function.总之,有人可能遇到的唯一性能问题是使用匿名 function 而不是 static function。

For example:例如:

const elements = []

elements.forEach((el) => {
  // a new handler is created with each iteration
  el.addEventListener('click', () => { /* some logic */ }) // anonymous function
})

// static function
const logic = () => {
  /* some logic */
}

elements.forEach((el) => {
  // result in smaller memory consumption because there is only one handler
  el.addEventListener('click', logic)
})

So, we have to be careful when using anonymous function inside a loop因此,在循环中使用匿名 function 时必须小心

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Memory_issues https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Memory_issues

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM