umop
umop

Reputation: 2192

AS3 object memory usage with static vs. instance methods

This has been a long-standing curiosity of mine, and I haven't gotten around to profiling to find out, and haven't seen it asked yet (for AS3):

Let's say that I have a class:

class MyClass {
   public function myMethod():String {
       return "some return value";
   }
}

which will be instantiated a lot of times:

for (var i:Number = 0; i < 10000; i++) {
   var myObject:MyClass = new MyClass();
   trace(myObject.myMethod);
}

Will changing myMethod to static have any change on the memory footprint of my app?

Is mxmlc smart enough to make a single reference to the function?

Basically, if I keep my method non-static will there be:

  1. No difference from a static version the method as far as memory is concerned
  2. 10,000 small instance references to a single function
  3. 10,000 function bytecode duplicates

in memory?

Upvotes: 4

Views: 1298

Answers (1)

Juan Pablo Califano
Juan Pablo Califano

Reputation: 12333

Yes, there'll be a difference in memory usage. Basically, because in one case you have one class and in the other one you have one class and 10,000 instances.

The code for the function itself will not be duplicated 10,000 times, though. There's just one function in memory in either case. Leaving semantics aside, an instance method is pretty much a static function that is passed a reference to the instance as its first parameter.

This parameter is hidden from you in Actionscript, as it in most languages (though others, like Python, I think, make you declare a self/this parameter in the function definition; you don't have to pass it explicitly at call time though).

Each object stores a reference to its methods (the methods declared in the actual runtime type and also inherited methods), usually in a structure called a vtable. The protocol for calling these methods usually involves finding the function in the table and calling it passing a reference to the this object on which the method is invoked, plus the rest of the arguments (if any).

At any rate, the static option could be a legitimate choice in some cases (the most obvious is when you have no state to keep, so you really don't need an object), but in general, an instance method is more flexible and less restrictive. Anyway, I'd say in almost every case it'd be rather unwise to choose one option or the other based on which one takes less memory.

Upvotes: 6

Related Questions