Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
Actionscript 3: Function Overhead
Nov 16, 2010ProgrammingComments (0)
Functions are useful tools that allow you to reuse code, reducing file size and keeping your application better organized. There is a trade-off however, and that is function overhead. An Actionscript 3 application will take a small hit in performance when moving a section of code out of the normal flow of the program and into a function.

This hit is very minimal in most cases, so you shouldn't avoid using functions by any means. For example, if you're only calling a function once per frame the overhead will be non-existent. Code organization is more important in these cases.

A case where function overhead could become a problem is when a function is called many times per frame. Perhaps you have a function that calculates a vector for projectiles, and you have thousands of projectiles being created per frame at times. In this case, it may be better to include the vector calculation in with the normal flow of code and avoid using a function, even if that vector calculation needs to be in a couple different areas.

Unfortunately the actual performance difference is difficult to measure. The following test took 572 milliseconds:

var i:int = 0;
var xPos:Number = 10;
var yPos:Number = 15.2;
var speed:Number = 10;

var time1 = new Date();
for(i = 0; i < 100000; i ++)
{
vector();
}
var time2 = new Date();
trace(time2 - time1);

function vector():void
{
var radians = Math.atan2(158.9 - 24.2, -29.8 - 18.1);
var vX = Math.sin(radians) * speed;
var vY = Math.cos(radians) * speed;
xPos+= vX;
yPos+= vY;
}

While moving the function body code into the loop resulted in 536 milliseconds:

var i:int = 0;
var xPos:Number = 10;
var yPos:Number = 15.2;
var speed:Number = 10;

var time1 = new Date();
for(i = 0; i < 100000; i ++)
{
var radians = Math.atan2(158.9 - 24.2, -29.8 - 18.1);
var vX = Math.sin(radians) * speed;
var vY = Math.cos(radians) * speed;
xPos+= vX;
yPos+= vY;
}
var time2 = new Date();
trace(time2 - time1);

This is with 100,000 iterations of the code. Less iterations results in a smaller performance gap (naturally), but the results are not measurable much lower than that. If you're only calling a function a small number of times per frame, don't expect any noticeable performance hit from function overhead.



One more note related to functions. Because Actionscript 3 always passes primitive variable types by value (including Booleans, Integers, and Numbers), be careful when using a function that takes any of these as arguments. You will actually be initializing (temporarily for local space only) variables whenever you call the function, which could also impact performance.
Comments (0)
Add a Comment
No comments yet