AS3: Inefficient to make too many references across classes?

68 Views Asked by At

I was told once that I should avoid referencing properties and such of my main game class from other classes as much as possible because it's an inefficient thing to do. Is this actually true? For a trivial example, in my Character class would

MainGame.property = something; MainGame.property2 = something2; MainGame.property3 = something3; //etc.

take more time to execute than putting the same in a function

MainGame.function1();

and calling that (thereby needing to "open" that class only once rather than multiple times)? By the same logic, would

something = MainGame.property; something2 = MainGame.property;

be slightly less efficient than

variable = MainGame.property; something = variable; something2 = variable;?

1

There are 1 best solutions below

0
On

Think of referencing things as of operations. Every "." is an operation, every function call "()" is an operation (and a heavy one), every "+", "-" and so on.

So, indeed, certain approaches will generate more efficient code than other ones.

But. The thing is, to feel the result of inefficient approach you need to create a program performing millions of operations (or heavy tasks of the appropriate difficulty) each frame. If you are not parsing megabytes of binary data, or converting bitmaps, or such, you can not worry about performance. Although worrying about performance and efficiency is generally a good thing to do.

If you are willing to measure the efficiency of your code, you are free to measure its performance:

var aTime:int;

var a:int = 10;
var b:int = 20;
var c:int;
var i:int;
var O:Object;

aTime = getTimer();
O = new Object;

for (i = 0; i < 1000000; i++)
{
    O.ab = a + b;
    O.ba = a + b;
}

trace("Test 1. Elapsed", getTimer() - aTime, "ms.");

aTime = getTimer();
O = new Object;
c = a + b;

for (i = 0; i < 1000000; i++)
{
    O.ab = c;
    O.ba = c;
}

trace("Test 2. Elapsed", getTimer() - aTime, "ms.");

aTime = getTimer();
O = new Object;

for (i = 0; i < 1000000; i++)
{
    O['ab'] = a + b;
    O['ba'] = a + b;
}

trace("Test 3. Elapsed", getTimer() - aTime, "ms.");

Be prepared to run million-iteration loops so that total execution time exceeds 1 second, otherwise the precision will be too low.