Using AS3 Object Memory Using Static vs. Methods instance

This is my long-standing curiosity, and I did not get the opportunity to profile to find out, and have not yet seen it (AS3):

Say I have a class:

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

which will be repeated many times:

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

Is changing myMethod to the memory size of my application?

Is mxmlc smart enough to make one link to this function?

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

  • Differences from the static version of the method in relation to memory
  • 10,000 references to small instances for one function
  • 10,000 duplicate bytecode functions

in mind?

+4
source share
1 answer

Yes, there will be a difference in memory usage. Basically, since in one case you have one class, and in the other - one class and 10,000 instances.

The function code itself will not be duplicated 10,000 times. In both cases, there is only one function in memory. If we leave semantics aside, the instance method is pretty much a static function that passes the reference to the instance as its first parameter.

This parameter is hidden from you in ActionScript, as in most languages ​​(although others such as Python, I think, force you to declare the self / this parameter in the function definition, you do not need to miss it explicitly during the call, though).

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

In any case, a static parameter may be a legitimate choice in some cases (the most obvious is that you have no state to save, so you really don't need an object), but in general the instance method is more flexible and less restrictive. In any case, I would say that in almost every case it would be unreasonable to choose one or the other option, on the basis of which there is less memory.

+6
source

All Articles