Preventing function calls brings performance
It isn't a secret. The overhead of function calls decreases the performance of your programs. So prevent them where ever you can. In software design encapsulation and modularity are two major, but oppositional topics. Good design finds the well balanced middle.
With some lines of code from my current project I want to show you how to prevent function calls at the usage of event dispatching. In my project I have one class dispatching an event to a lot of other objects. Each of these objects has got an ID and each event is just for one of them.
The easy way to code this is to register each object for the event and in the object's event handler I check the ID saved in the event object and skip the handler if the ID is not corresponding to the ID in the event object.
- ...
- for ( var i:int = 0; i < 200000; i++) {
- arReceivers.push( new Receiever(i) );
- sender.addEventListener( "test", arReceivers[i].evt );
- }
- ...
- ...
- public function evt(e:MyEvent):void {
- if (e.id != this.id )
- return;
- // the event is for me
- }
- ..
In my test code I have 200,000 receiver objects and this codes leads two 200,000 function calls.
A better way of coding is to register one "global" handler for the event and to find the corresponding receiver object in this handler.
- ...
- sender.addEventListener( "test", evt );
- for ( var i:int = 0; i < 200000; i++) {
- arReceivers.push( new Receiever(i) );
- }
- ...
- ...
- public function evt(e:MyEvent):void {
- for ( var i:int = 0; i < arReceivers.length; i++) {
- if (e.id == arReceivers[i].id ){
- arReceivers[i].evt(e);
- break;
- }
- }
- }
- ...
In this code just two function calls occur independent from the number of receiver objects.
This is the last post for 2009. I wish you a happy new year and keep curious in 2010 :-)


