另一个答案,因为为什么不呢:)
package
{
import flash.display.Sprite;
import flash.system.System;
import flash.utils.describeType;
import flash.utils.Dictionary;
import flash.utils.getTimer;
public class TestDescribeType extends Sprite
{
private var m_cache:Dictionary = null; // a cache that says if we've used this object before
private var m_functions:Dictionary = null; // the functions for this object
public function TestDescribeType()
{
this.m_cache = new Dictionary;
this.m_functions = new Dictionary;
this.profile( this, this.one );
this.profile( this, this.two, 4.5 );
this.profile( this, this.three, 4.5, "hello" );
this.profile( this, this.four, 4.5, "hello" );
}
// profiles how long it takes a function to complete
public function profile( obj:*, func:Function, ...params ):void
{
// if we don't have this object in our cache, parse it
if ( !( obj in this.m_cache ) )
this._parse( obj );
// get our functions dictionary and get our function name
var dict:Dictionary = this.m_functions[obj];
var funcName:String = ( dict != null && ( func in dict ) ) ? dict[func] : "Unknown func";
// start our timer and call our function
var startTime:int = getTimer();
func.apply( null, params );
trace( " " + funcName + " took " + ( getTimer() - startTime ) + "ms to finish" );
}
// some test functions
public function one():void { trace( "one()" ) }
public function two( one:Number ):void { trace( "two(" + one + ")" ) }
public function three( one:Number, two:String ):void { trace( "three(" + one + ", " + two + ")" ) }
public function four( one:Number, two:String, three:int = 0 ):void { trace( "four(" + one + ", " + two + ", " + three + ")" ) }
// parses a class/object and removes all the functions from it
private function _parse( obj:* ):void
{
// get our xml
var x:XML = describeType( obj );
this.m_cache[obj] = true; // we don't need to store the xml, just that we've parsed it
// find our functions
var funcs:Dictionary = new Dictionary;
for each( var mx:XML in x.method )
{
var name:String = mx.@name;
var func:Function = obj[name] as Function;
// store the function with the name etc in our dictionary
funcs[func] = name;
}
// store our functions
this.m_functions[obj] = funcs;
// kill our xml object immediately - helps memory
System.disposeXML( x );
}
}
}
运行代码以了解它的作用。基本上,我们describeType()
在第一次遇到对象时对它执行 a 操作,并取出它的所有功能。然后,该profile
函数获取我们想要的 - 我们检查缓存以获取正确的名称,然后调用它。
比在对象上抛出错误(初始)更快的优点describeType()
是有点慢,但它是一次性的,如果你真的想要,你可能会添加一个预处理步骤。
您需要对其进行返工,以便describeType()
唯一适用于类,而不适用于对象(就好像您有 10 个 Sprite,它将执行 10describeType()
秒)。如果您这样做,则m_functions
需要为每个对象设置字典,否则(func in dict)
如果您明白我的意思,那么除了第一个对象之外的所有对象实例的检查都将失败。
无论如何,你明白了:D