Monday, 4 February 2008

XMLList length() gotcha

I thought I'd pass on a tip on traversing nodes in E4X. Consider the following common array loop:

[as3]
for (var i:uint=0; i<myArray.length; i++)
{
// do something here
}
[/as3]

Now, take a similar approach to E4X:

[as3]
var myChildren:XMLList = myXML.item;
for (var i:uint=0; i<myChildren.length(); i++)
{
// do something here
}
[/as3]

On the face of it, there's nothing wrong with the above code. It compiles fine, it works fine. Until you traverse 1,000-or-so nodes. Not so good.

Investigating this shortfall, you'd be forgiven for believing E4X isn't as quick as maybe you thought it was. But simply, calling length() on the above calls it 1,000 times, meaning E4X has to run through and count its children, 1,000 times - whereas an array.length is just a simple property - comparing it with the current state of i. So the following is a far more efficient way to go about it:

[as3]
var myChildren:XMLList = myXML.item;
var myLength:uint = myChildren.length();
for (var i:uint=0; i<mylength; i++)
{
// do something here
}
[/as3]

This cuts down processing of 1,000 nodes to 20% of its original timings.

No comments:

Post a Comment