Gaming Your Way

May contain nuts.

Little as3 speed test

I was just tinkering and wondered what would be quicker, using clone() on a Rectangle or just copying each property by hand.

Totally blown away by the difference,

 

import flash.utils.getTimer;
import flash.geom.Rectangle;

var time:Number = getTimer();

function runClone():void{    
    var rect:Rectangle=new Rectangle(0,0,100,100);
    var destRect:Rectangle=rect.clone();
    time = getTimer();
    for (var i:int = 0; i < 10000000; i++) {
        destRect=rect.clone();
    }
    trace("runClone: ", (getTimer()-time));
}

function runCopy():void{    
    var rect:Rectangle=new Rectangle(0,0,100,100);
    var destRect:Rectangle=rect.clone();
    time = getTimer();
    for (var i:int = 0; i < 10000000; i++) {
        destRect.x=rect.x;
        destRect.y=rect.y;
        destRect.width=rect.width;
        destRect.height=rect.height;
    }
    trace("runCopy: ", (getTimer()-time));
}

runClone();
runCopy();

And here's my results ( Please feel free to post your own, or to point out anything dumb I may have done to affect the outcome )

runClone:  11567
runCopy:  65

Squize.

 

 

Comments (2) -

  • Louis-Philippe Maurice

    11/16/2007 3:38:08 AM |

    You did forget something very important: rect.clone() creates a new instance of Rectangle. Your runCopy() function doesn't instantiate a new Rectangle every loop, it only uses the same instance and sets properties. The following is still faster than a simple clone(), but the margin is far less impressive.
    function runCopy():void{    
        var rect:Rectangle=new Rectangle(0,0,100,100);
        var destRect:Rectangle;
        time = getTimer();
        for (var i:int = 0; i < 10000000; i++) {
        destRect = new Rectangle();
            destRect.x=rect.x;
            destRect.y=rect.y;
            destRect.width=rect.width;
            destRect.height=rect.height;
        }
        trace("runCopy: ", (getTimer()-time));
    }

    I get:
      runClone: 8522
      runCopy: 7901

  • Squize

    11/16/2007 3:09:42 PM |

    Ah good point mate. Never post when you're really tired :)

    Still weird that creating a new instance, and then shoving the values in by hand is quicker than cloning though. Clone must just have quite an overhead for type checking and the like.

    For my slightly flawed example it still runs valid for my current project, where I only need one duplicate of the rectangle and need to alter a couple of properties of it every frame, so I just create the duplicate instance in the constructor.
    I was mainly curious to see where the trade off point would be between clone and copying properties directly. I figured that for example changing just destRect.x would be quicker than clone() but wasn't sure how many you could alter before clone was quicker.

    All of them it seems :)

    Thanks for the reply and clearing up the flaw with the test mate.

Comments are closed