index = list.index;
len = list.length;
while (index < length) {
It's a problem with len/gth, you overlooked the 'length' in the
while() when you renamed it to 'len'.
Below is the reworked testing class. It creates the array in the
beginning, then waits 30 frames before testing the two methods, taking
turns, one test per frame.
The result I'm getting is that recursion consistently is about 20%
faster than my iterative function (mtasc compiled, running in the
Linux plugin, which still is version 7). That's a bit of a surprise
since it was 10% slower in Danny's test, but then, it's different
compilers.
If you want to compile it in the Flash IDE to compare, take an empty
.fla, import TestArray, and call TestArray.main(). My version is at
<http://www.snafoo.org/tmp/flatten.swf>.
Mark
class TestArray extends Array {
public static var testarray : Array;
public static function main () : Void {
var ta = TestArray.testarray = TestArray.randomArray( 100000 );
_root.createTextField( "tf", 1, 0, 0, 1024, 768 );
var cntr = 0;
_root.onEnterFrame = function () {
if( cntr++ > 30 ) {
var n = (cntr % 2);
var start = getTimer();
if( n ) {
ta.flatten2();
} else {
ta.flatten();
}
var dur = getTimer() - start;
_root.tf.text += "\n" + (n ? "flatten2" : "flatten") +
": " + dur;
}
if( cntr > 70 ) {
delete this.onEnterFrame;
}
};
}
public static function randomArray(p) : Array {
var a = new TestArray;
for (var i = 0; i < p; i++) {
if (Math.random() * 2 < Math.random() * 5) {
a.push(i);
} else {
a.push(TestArray.randomArray(Math.ceil(
Math.random() * 3 ) ));
}
}
_root.tf.text += "length: " + a.length;
return a;
}
public function flatten (r) : Array {
if (!r) r = [];
var n = this.length;
for (var a = 0; a < n; a++) {
if (this[a] instanceof Array) {
r.push(this[a]);
} else {
this[a].flatten(r);
}
}
return r;
};
public function flatten2 () : Array {
var outArray : Array = [];
var list = this;
list.index = 0;
var item : Object;
var index : Number;
var length : Number;
do {
index = list.index;
length = list.length;
while( index < length ) {
item = list[ index++ ];
if( item instanceof Array ) {
item.parent = list;
list.index = index;
list = item;
index = 0;
length = list.length;
} else {
outArray.push( item );
}
}
} while( list = list.parent );
return outArray;
}
}
<<<
_______________________________________________
[email protected]
To change your subscription options or search the archive:
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders
Brought to you by Fig Leaf Software
Premier Authorized Adobe Consulting and Training
http://www.figleaf.com
http://training.figleaf.com