Search code examples
javascriptjqueryeventsactionlisteneronclicklistener

Does adding too many event listeners affect performance?


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


Solution

  • 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