简体   繁体   中英

event.target with element.addEventListener

In a solution I am currently working on I originally was binding event listeners to many targets within the same container. I wanted to see if any of you have seen significant performance gains in using a single event listener and utilizing the target of the event in order to save the overhead of a large amount of event listeners.

In short, are there significant performance gains in JavaScript when limiting the number of event listeners.

There are tradeoffs between using event propagation with a single event handler and individual event handlers on each object. Which tradeoff is best for you depends entirely on your individual circumstances. There is no single answer that is best for all situations.

At runtime, an individual event handler attached to each object will work the fastest. Since it is attached directly to the object of interest, the system has essentially no work to do to know that the event handler should be fired.

At installation/setup time, the single event handler attached to a parent will be faster to initialize than initializing an event handler on every single object.

So, you basically have a small tradeoff between faster setup time vs. faster execution at the time of the event.

In the end, the time execution difference is probably small enough to be meaningless unless you have thousands of objects. I'd suggest selecting the option that makes the cleanest, simplest code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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