Reputation: 10516
It seems more efficient to store events on the dispatcher if they're never going to change. Isn't creating them costly? Is there some kind of information I'm losing if I dispatch an already-stored event?
Upvotes: 1
Views: 257
Reputation: 38751
Essentially what your asking is a specific use case of object pooling, and the performance of object pooling vs. object creation. Languages like Java don't get much benefit from object pooling because Java does this for you. And does it better than if you were to do it on your own. In fact Java engineers have made it very clear you shouldn't do this because Java allocates, scales, and handles thousands of objects better than you can. That's the whole point of GC. Object allocation in Java is already doing pooling for you, but at a lower level that's why memory allocation in Java and other languages is way faster than C. Every object allocated in Java comes from a ready made memory pool by the JVM.
http://www.ibm.com/developerworks/java/library/j-jtp09275.html?ca=dgr-jw22JavaUrbanLegends
Another reason events are created at dispatch time, instead of caching them, is they carry parameters in them that change between each dispatch. For example, what character was typed, where the mouse was clicked, etc. Recycling events might sound like a good idea until you do it, and all of a sudden you're sending old information with the wrong event. Better to just new that event up each time and have it properly initialize itself with the right data. It's simpler for the author and less error prone.
There are also technical problems you might encounter if you reused events. Event cancellation schemes usually store that information in the event that is modified after dispatch by some listener. In actionscript you can say event.preventDefault() to affect the chaining of event listeners. What happens if you start reusing that event after preventDefault has been called? And at what time is it safe to say this event isn't being used by a listener that has yet to fire (callLater/invokeLater makes it hard). There's no callback in either Java/Actionscript that says this event is ok to reuse (no reclamation semantics to return the object to the pool).
That's not to say you could find a case where holding onto the event and reusing it performs better. But, just because it's faster for those high performance cases doesn't mean it's a good idea for everything every time. Remember don't optimize until you know there's a problem.
Upvotes: 4