views:

209

answers:

3

My Friend and I have this debate about it is faster in AS3 to pass this to another object to be able to have communication/interaction between the two or if Events are the way to go. While using Events to accomplish this task is pretty standard, here is some dummy code to illustrate the question:

   public class ClassA{

   public var items:Array = new Array();
      public function classA(){
        items.push(new ClassB(this));
      }

      public function poke(){
         trace('yes, can i help you?');

         this.items.speak();
      }
   }



   public class ClassB{
      public var parentObject:Object;
      public function classB(pobj:Object){
        parentobject = pobj;
        parentobject.poke();
      }

      public function speak(pobj:Object){
          trace('nothing, forget it!');
      }
   }

So if ClassA gets constructed it will push a new object of ClassB into its items-Array. ClassB's constructor calls the Class-A instance's poke() which immediatly calls the ClassB's speak()-function.

I don't what the correct term for this method is (or if there is even is one). My friend says he feels his code runs faster when using many objects but I doubt it because I think this might confuse the Garbage Collector.

What are your thoughts on this topic and what sources would you recommend to read on this topic?

+8  A: 

The difference is that Events decouple your classes better. Read about Coupling.

In the code you have given, your Class B has to know what a Class A is, and your Class A has to know what your Class B is.

With events, the only thing the classes need to know is where it can find an instance of an object to add a listener to it. It does not need to know what functions to call, or call any functions other than addEventListener.

The dispatching object does not know anything about the listener.

The Events way of passing messages gets rid of tight interdependence of classes, which can lead to problems with maintenance and bug finding. It's better to know as little as possible about another object. Events are great because the dispatching object can publicize what is happening without exposing functions or internal details to other objects.

See: Loose Coupling and Cohesion.

Kekoa
+1  A: 

Yeah, in the code sample, you've basically got a single functional unit written as two objects. Communication is probably measurably faster, but I wouldn't think it would be humanly noticeable.

Overall, this sort of tightly coupled approach would limit the complexity of a given application so severely that there wouldn't ever be any actual need to optimize messaging speed.

Ross Henderson
A: 

Agree with kekoav and rhtx's answers, but I'd also add that you're trying to optimise something that doesn't need optimising. As a last resort you may want replace events for simple method calls if you actually noticed a slowdown, but to guess at what might be faster or slower is pointless.

Iain