Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...