Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a potential slowdown using too many listeners?

In a program I'm writing, I'll have at least 64 JButtons. Would it be better to write one ActionListener or have 64 of them, one for each? I don't think that I'm going to use one listener for each JButton route, but it did make me wonder about something. Is a there point at which too many listeners can actually impair performance and if there is such a thing, how many would it take?

like image 462
Tom K Avatar asked Oct 19 '22 07:10

Tom K


1 Answers

Each JButton is going to hold a list (or array, or collection or however it is implemented) of references to its listeners while not being aware of listeners for other buttons. When an event happens the button calls to its listeners. So having many listeners for other buttons will not slowdown the calling of the listeners. So no slowdown here.

The only source of slowdown I can foresee are cache misses. Having many listeners with different code would mean more cache misses.

But having a single listener with a lot of convoluted code to handle all cases might be even slower. You still have a lot of bytecode and you may be having a lot more branching than in the case of multiple listeners.

Conclusion : Make your listeners cohesive. Have different listeners for dealing with different actions and use the same listener for buttons performing a similar action. It will give you both better code and speed.

like image 72
Anonymous Coward Avatar answered Oct 27 '22 00:10

Anonymous Coward