What is faster plain objects or strongly typed obj

2019-02-27 10:27发布

问题:

So is

public var user:Object = {}; 
user["firstName"] = "Bill";
user["lastName"] = "Cosby";

slower than if I have a value object like User?

var user:User = new User();
user.firstName = "Bill";
user.lastName = "Cosby";

回答1:

public function speedTest():void               
{            
    var typedObjects:Array = [];
    var dynamicObjects:Array = [];
    var typedObject:User;
    var dynamicObject:Object;
    var i:int = 0;
    var n:int = 10000;
    for (i; i < n; i++)
    {
        dynamicObject = {};
        dynamicObjects.push(dynamicObject);
        typedObject = new User();
        typedObjects.push(typedObject);
    }
    // typed
    var time:int = getTimer();
    i = 0;
    n = 10000;
    for (i; i < n; i++)
    {
        typedObject = typedObjects[i];
        typedObject.firstName = "Bill";
        typedObject.lastName = "Cosby";
    }
    var end:int = getTimer() - time;
    trace("TypedObject Time: ", end/1000, "sec");

    // untyped
    time = getTimer();
    i = 0;
    n = 10000;
    for (i; i < n; i++)
    {
        dynamicObject = dynamicObjects[i];
        dynamicObject["firstName"] = "Bill";
        dynamicObject["lastName"] = "Cosby";
    }
    end = getTimer() - time;
    trace("DynamicObject Time: ", end/1000, "sec");
}   

Simple speed test shows that TypedObject (User) is roughly 3-3.5x faster than UntypedObject ({}), but it's nothing you'd ever notice in the day-to-day. Try out Grant Skinner's Performance Test Harness to run some better/advanced tests :).

3 simple trial runs:

TypedObject Time:  0.002 sec
DynamicObject Time:  0.007 sec
TypedObject Time:  0.002 sec
DynamicObject Time:  0.006 sec
TypedObject Time:  0.002 sec
DynamicObject Time:  0.006 sec

Verdict: Typed is faster than Untyped.



回答2:

More importantly than any speed benefits, strong typing gives you compile-time type checking so you don't typo property names - saving a lot of developer time, which is far more expensive than clock cycles.

Though yes, static typing does carry speed benefits as well.