views:

22

answers:

1

Hey all,

I'm attempting to write a performance testing function that can take any function, run it X times and spit out how long it took that function to run in AS3. I've got it working just fine if a function doesn't take any parameters but it comes up with an error otherwise.

Here's the code:

public static function testFunction(targetFunction : Function, object : Object, ... parameters)
{
    var iterations : int = 10000;
    var i : int = 0;
    var time0 : Number = 0;
    var time1 : Number = 0;

    if (parameters.length == 0)
    {
        time0 = getTimer();

        for (i = 0; i < iterations; ++i)
        {
            targetFunction();
        }

        time1 = getTimer();
    }
    else
    {
        time0 = getTimer();

        for (i = 0; i < iterations; ++i)
        {
            targetFunction.call(object, parameters);
        }

        time1 = getTimer();
    }

    trace("Took " + (time1 - time0) + "ms to complete " + iterations + " iterations");
}

This works just fine: testFunction(timelineMethod)

But something like this: testFunction(game.addGameState, game, gameState); // gameState would be the parameters

throws this: TypeError: Error #1034: Type Coercion failed: cannot convert []@2f46491 to g2d.GameState. at Function/http://adobe.com/AS3/2006/builtin::call()

It seems like game or gameState wouldn't be valid instances, but they definitely are. So I'm assuming it doesn't somehow know what object the method to be tested belongs to and its throwing this error.

Any ideas?

+2  A: 

function.call requires a list of parameters, the same as if you were to call the function normally.

If you want to pass an array of parameters, you should use function.apply instead.

Anon.
Just that simple huh? Seems to be working. Thanks a bunch.
Scott
+1 Scott, please accept the answer if its correct.
Tyler Egeto