I just heard from co-workers that using the length property directly in the validation, has lower performance than assigning the value to a variable:
for(var i:int=0;i<array.length;i++)
trace(String(i));
for(var i:int=array.length-1;i>-1;i--)
trace(String(i));
They actually claim that, the second loop will iterate over the array “up to 90% faster”, is any of this true??
This question can apply for any language, but im only interested on AS3 behavior for this, especially on ArrayCollections.
The reason for this issue is a lot more interesting than you would expect.
Examine the following code, it includes seven tests:
Here are the results:
Why do you suppose the last one is so terribly slow when compared to the rest?
It is not because the Array re-calculates the length each time, that would be silly.
Read this:
The reason is in the implementation
The other six tests use a regular public member of a class.
Array’s use getter and setter functions to retrieve the length value.
If you continue to elaborate the test, you will see function calls cost precious time.
When you need more performance, you sometimes have to rely on inline code.
That is is true almost every time. That is because the processor has to ‘jump’ to a different area in the code, create a new scope and some additional reasons.
Why is inlining considered faster than a function call?
If you check the length implementation for vector, you will see it is just a public member unlike array (getter and setter) functions. Getters and Setters are better for extensibility, they can make your life a lot easier if you decide to inherit from a class, setters can also prevent certain errors by checking the values. Nothing beats a public property for speed.