Reputation: 39456
I have a linked list class that stores a linked collection of entities.
I've added an iterate()
method to this class which I am sceptical of. It accepts a function as its only argument, which should accept an instance of Entity
only.
i.e.
list.iterate(function(entity:Entity)
{
trace(entity.id);
});
I'm concerned about this method because I'm not sure what will happen to the function I've given to iterate()
in this case. Will what I'm doing hurt the performance or memory usage of my game at all when compared to doing my iterations manually like so?:
var i:Entity = list.first;
while(i != null)
{
trace(i.id);
i = i.next;
}
Any information on this is appreciated.
Upvotes: 2
Views: 195
Reputation: 1768
Though anonymous functions are common in many languages it's a common convention not to use them. They make code less clear, they are hard to debug and they are slow as hell.
And it's not even a matter of calling a nested function. It's ofcourse slower than NOT calling a function but the real reason is that ff there's an anonymous function declaration in a class method AS3 compiler creates special Activation object in bytecode and virtual machine has to save all local variables to make them accessible to this function. This makes this particular method slow. Even if you don't call anonymous function inside but just have it declared.
As all optimization techniques they are to be followed correctly. If you got a closure called like once per frame you will not notice any slowdowns. But as I see you got a linked list which might be long and iterated multiple times per frame. This might cause some performance loss.
Upvotes: 0
Reputation: 27506
list.iterate(function(entity:Entity)
{
trace(entity.id);
});
is worse than
var i:Entity = list.first;
while(i != null)
{
trace(i.id);
i = i.next;
}
if you have a similar while loop in your iterate function because you add the overhead of calling the nested function.
And the while loop will be I guess more performant than using something like this:
list.iterate(nonStaticNonNestedFunction);
because there is still the overhead of calling a function, even if it is less than the overhead of the nested function.
Upvotes: 1
Reputation: 9897
Nested functions are closures, and closures are slow to call. If you need performance, your best bet are non-static non-nested functions (test it with getTimer
if you don't believe Jackson Dunstan's tests.)
Upvotes: 1