More testing on Actionscript’s Math class
As you may have noticed I’m somewhat critical regarding the AS3 Math class. I’m a bit sick to be honest and work was flowing as I wanted to so I took 30 minutes off to test some stuff.
Flooring a number
Getting the nearest low integer of a number is usually achieved with Math.floor(number). If we didn’t have it, we would probably typecast the number to an integer and get the same result. So I looped both methods one million times and measured the results.
Math.floor(number) performed around 150 milliseconds
int(number) performed around 5 miliseconds
Now the bad news is that this works for positive numbers, using int(number) for negative signed numbers doesn’t produce a floored integer. For example int(-2.4) returns -2 where it should return -3.
Rounding a number
Rounding a number will return the closest integer of that number. Again this is usually achieved with Math.round(number) but we can also do this:
One million iterations after the results are as follow:
Math.round(number) took around 165 milliseconds
int(number + 0.5) took around 5 miliseconds
Same issue applies regarding negative signed numbers though, so keep that in mind, but the question is…
Are you feeling the urge of writing a new Math class?
This way we could deal with both performance and doing some arrangements to make negatives work correctly. Problem with this is that we will be calling a static method from an external class. A full working rounding method called one million times took 180 milliseconds against the 165 milliseconds from Math.round(number) method, so there’s loss instead of gain.
Bottom line is that this kind of stuff is a bit like using multiplications over divisions. Depends on a lot of stuff. If your display objects move on a positive x and y axis, you can do it like there’s not tomorrow, just typecast to integer whatever you need to round, but all in all, unless you have millions of Math class operations to do, you won’t even notice the difference.
See you soon,
Vlad
Posted: August 9th, 2009
at 12:00am by Vlad
Tagged with FlashGameBlogs, Software Engineering, Testing
Categories: The code of VGS
Comments: No comments
The “make it fast” demo
Yesterday I wrote about making code work then nice then fast. I believe that the fast part was not that obvious on how it can impact your overall game performance. So I decided to put up a simple test that is a demonstration of a real world example.
We will be dealing with two of the finest cpu-cycle hogs in the Actionscript world and you can pretty much apply it to every thing game development related.
The main code
I defined this as the document class of some flash file and then started to add methods to test. Each method was a variation of the previous. At each test I simply added the function call to the constructor. Simple and fast, here’s the first method…
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.utils.getTimer;
public class PerfTest extends MovieClip
{
public function PerfTest()
{
// The start time
var startTime:int = getTimer();
// Test method call goes here
// Traces the test results
trace("Test concluded in " + String(getTimer() - startTime) + " miliseconds");
}
}
} |
Calculating a distance: 1750ms
The basic test is to calculate the distance between two points. I simply wrote every single detail of code I needed inside a 1 million iteration ‘for’ loop. I created new points, calculated the right triangle legs and then the hypotenuse. Every thing should be crystal clear. One million distances calculated got an average time of around 1750 miliseconds.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private function DistanceTest1()
{
for (var test:int = 1; test <= 1000000; test++)
{
var point1:Point = new Point(100, 100);
var point2:Point = new Point(200, 200);
var leg1Length:Number = Math.pow(point1.x - point2.x, 2);
var leg2Length:Number = Math.pow(point1.y - point2.y, 2);
var distance:Number = Math.sqrt(leg1Length + leg2Length);
}
} |
Skipping object creation: 505ms
This is one of the biggest issues, one that is often a problem. I’ve read about it, I’ve even defended that object pooling is not that important in many games and then once my code created around 200 objects in less than a second I had to rethink it. Add to that that the objects created had things to do on their own, like moving, colliding and sorts and I got myself a bit of a performance issue.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private function DistanceTest2()
{
var point1:Point = new Point(); // Created outside the loop
var point2:Point = new Point(); // Created outside the loop
for (var test:int = 1; test <= 1000000; test++)
{
point1.x = point1.y = 100; // Reused object
point2.x = point2.y = 200; // Reused object
var leg1Length:Number = Math.pow(point1.x - point2.x, 2);
var leg2Length:Number = Math.pow(point1.y - point2.y, 2);
var distance:Number = Math.sqrt(leg1Length + leg2Length);
}
} |
The only thing done is here to take the creation of new objects from the loop. Note that I’m not reusing Numbers because the impact is on the creation of an object with the ‘new’ operator.
Other ways to do math: 180ms
The result is the same but the time taken to do it isn’t. Math.pow(x,y) and other methods from the Math static class are very heavy. There are times where it is too troublesome not to use it, but if you can avoid it, do so.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private function DistanceTest3()
{
var point1:Point = new Point();
var point2:Point = new Point();
for (var test:int = 1; test <= 1000000; test++)
{
point1.x = point1.y = 100;
point2.x = point2.y = 200;
// Math.pow(x,y) substituted with a simple multiplication
var leg1Length:Number = (point1.x - point2.x) * (point1.x - point2.x);
var leg2Length:Number = (point1.y - point2.y) * (point1.y - point2.y);
var distance:Number = Math.sqrt(leg1Length + leg2Length);
}
} |
One last math optimiztion: 20ms
Calculating square roots is heavy stuff, really heavy stuff. This is not the exact same case as the one pointed previously, but it is very similar. The main difference here is that if you are returning the distance, that is not the correct distance at all. It is the distance powered by two. If you want to use this distance to check against something, you’ll need to power that something also to keep it fast.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private function DistanceTest4()
{
var point1:Point = new Point();
var point2:Point = new Point();
for (var test:int = 1; test <= 1000000; test++)
{
point1.x = point1.y = 100;
point2.x = point2.y = 200;
var leg1Length:Number = (point1.x - point2.x) * (point1.x - point2.x);
var leg2Length:Number = (point1.y - point2.y) * (point1.y - point2.y);
// No square root is calculated, you need to take this into consideration
var distance:Number = leg1Length + leg2Length;
}
} |
Conclusions
I tried to address some common performance downfalls that happen very easily but that can be dealt with very easily also. We can argue that this is over one million iterations, but if you are using this kind of code for collision detection, that amount of iterations can happen sooner than you’d expect.
The real problem with performance in game development is not at all a matter of having millions of operations in one spot of your game loop like it is demonstrated here, but having several minor performance issues all around your code that is called from the game loop.
This is just a demo of the kind of things you should look for and solve. There are many others, some of it very game specific. When your game is working as intended, when the design is implemented, it’s time to make it fast because the game should be as smooth as possible and because you’ll probably and hopefully polish the game. That polishing often adds something to the game and that something needs breathing room to work out well.
Hope this helps,
Vlad
Posted: August 5th, 2009
at 12:00am by Vlad
Tagged with FlashGameBlogs, Testing
Categories: The code of VGS
Comments: 5 comments
The art of game development refactoring
Every thing that starts with “The art of…” sounds so cool doesn’t it? Can’t say I’m a real master at what I’m about to write. This “vision” appeared before my eyes when I made a question about game loop performance techniques in the Portuguese game development community. Out of many answers, one had this pearl of wisdom:
Make it work, make it nice, make it fast!
And I’ll be damned if this simple sentence didn’t influence me since that day… not so long ago.
How I handled my code before…
To put it in simple terms: my code was written to be as close to the end form from start. I coded all the possible performance tricks immediately, wrote reusable code asap and my refactoring was usually very short. This made all well planned projects to be coded in very short terms.
I always had one major problem though: every time the project needed one or more deeper changes I had to recode a lot and, naturally with the same degree of “end code” vision. This means that I used to pre-plan too much and that my code changes were not that agile. More than often this meant that the game was slave to the code and not to the design and this is usually a game killer.
After that sentence, all was different…
Make it work

First objective of every line of code: making it work, no matter what. Is it slow? Is it ugly? Often yes! Does it work? YES! And this is a good thing. Code that works as soon as possible offers you the possibility of being able to access if you need changes or not sooner. This is very important in game development, especially short development like with flash based games.
You will go through all the same design issues, but you’ll do it sooner, you can adapt sooner. That’s the whole point of agile development: you can make changes without compromising features changes or feature additions.
It is very important that you don’t do anything stupid, like having duplicated code. Be fast, don’t be sloppy. It’s OK if you are not paying attention to a lot of details and you are writing in the easiest possible form, but it is not OK if you are copy/pasting code and this is just an example.
Is it has intended? Is everyone happy with the current form?
If yes, refactoring is in order…
Make it nice
If everything is according to plan, you can, you should and you will (I command thee) refactor your code to make it nice. I’m very fashion victim code wise. I like my variables of the same context to have the same length for instance, but it is more than enough if you comment your code, cut the loose ends and have your code ready for you to forget about it. That’s right, move it away from your brain, you’ll need the room for the next iteration. If it is well documented and easy to read, you can return to it anytime.
Here’s a good cliche: Hold in your brain only the things you can’t have written down.

- As fast as this…
Make it fast
Well… now it’s the tricky part. Your code is probably not the fastest thing in the world, why? Well, you made what you were supposed make, you probably added changes to it, you commented it and made it nice and tidy, but maybe you have some stuff there that could use a little help. Actually I’m pretty sure you do. This is due mostly to the fact that making it work as fast as you can usually doesn’t mean you made it as fast as it can work. Wow… am I on a cliche thing or what?
Every piece of software needs its own set of performance tweaking. It can be anything really.
A world of performance tweaking stuff has been written, maybe I should add mine also one of these days, but there are things that are pretty common.
Heavy calculations come to mind… it’s quite common to use really heavy math operations on a per frame basis instead of pre-calculating this kind of stuff. If you have dozens of objects calculating sines and cosines, making divisions, calculating distances and so on, you will have a lot of performance tweaking ready to be made.
Object creation is a major issue with Actionscript also. A lot of the code snippets I find have new objects created inside some methods that are supposed to be called most if not all frames.
Another common issue is that a part of your code is bottle necking the rest, often causing frame drops. Identify what causes the bottleneck, then either run it from time to time, use a maximum iterations value or segment it in your game loop.
I guess I should just write some optimization articles soon or I can be here forever…
See you all soon,
Vlad
Posted: August 4th, 2009
at 12:00am by Vlad
Tagged with FlashGameBlogs, Software Engineering
Categories: The code of VGS
Comments: No comments
Bold Pixel Update: IT’S ALIVE!
It’s a bit more than an update. I can confirm that our engine is now born and is currently being used for the current contract project. I will be telling you more about it in the next couple of weeks as we fine tune it, but here’s a bit of info about it.
Basically I recoded most of the current engine in order to make classes more logical and easy to use. Coded proper singletons for all manager classes that had a use for that particular pattern, moved classes around to make the engine more tidy and commented all classes from top to bottom.
Added a couple of nice things, for instance, we had a Preloader class that was supposed to be extended to the preloader movieclips all games have. Problem with it is that preloaders from portals rarely fit this class. I recoded it to be a Load Manager class that handles all loading processes, from external files to the preloading while giving info about the current progress of it. This way I have one class that handles all loading needs (including preloading) and that doesn’t need to be extended… so sweet.
The Bold Pixel
Bold Pixel Engine is the name I selected to honour the work of my partner Marco. I’ll write a funny fact about it one of these days.
Anyway, Bold Pixel is our engine’s name as soon as I can call it a game engine, and now I can. The missing link was the blitting engine we have planned for some time.
The blitting engine is made of a texture manager, a layer manager, a render engine which handle textures, layers and entities. It currently supports frame independent animation for entities as well as rotation, pivot points per texture. A lot of thought was put in finding a good balance between flexibility, speed and reusability.
I’m quite happy with the results although moving the current project to this version of the engine is more work than I anticipated considering how well the actual staging of it went. Production is always tougher than staging I guess.
Later,
Vlad
Posted: July 27th, 2009
at 3:04am by Vlad
Tagged with Bold Pixel Engine, FlashGameBlogs
Categories: The code of VGS
Comments: No comments
From refactor to library
Or how to refactor the code from your last game to build up your reusable libs.
First and foremost, thanks to the people at FGL chat that brainstormed a jolly good topic to write about. This post also helps me to rethink my strategy about an issue I have with our core libs that I’ll hopfully address in the future as soon as I make sense.
Basic question is how do I handle the code I used in the previous game to reuse it… I’ll give several examples of how our core classes appeared or changed hoping that you find something useful for your own code and games.
In the beggining there was music
When we wrote Tech Wars, I had to write a music manager that would know when to change tracks. There are three tracks in Tech Wars, all with the same beats per minute, two share the melody but with different instruments and one has a slight variation of the melody. Each track served a part of the game, such has menus, level, and post-level.
Our current music manager has code from Tech Wars. That code evolved from a game specific class to a generic sound manager class and then to two separate classes: sound manager and music manager. These shifts occured as the next games needed or between projects.

What started with Tech Wars is now what we call the core, which is simply a bunch of abstract, cross-project oriented organization of directories and classes that goes from one project to another. It is not something you do, it is something you keep doing, building and evolving. That sound manager class was a bad case of refactoring, but a good start since we had no reusable AS code.
Generalization
To create your libs you should make each class abstract from the game code. This maybe trickier than it sounds. For instance, we have a Scene Manager. What it does is quite simple:
1. ensures that one and only one scene is running
2. ensures that one and only one dialog is running
3. ensures that when a scene is started the current scene and current dialog are closed
4. ensures that when a dialog is started the current dialog is closed
And this has to work in every game. To be sure that it works in every game I made sure that a scene or a dialog is always a movie clip that is linked in the fla library and that I can pass up to five arguments to it. I also made sure that the Scene Manager is a singleton.
Get yourself organized
To be sure that your code is generic, organize it! Create a structure outside your game logic, as an example, when I start a project I copy the core directory from the previous project to the root of the current project and I create a separate directory “game” where all the game specific classes go.
It’s that simple.
Refactoring
Refactoring plays a big role in all of this. Now that the core classes are a few and that most of the nasty work is done, the process of refactoring tunes it and adds to it.
Again… an example. Some hours ago I was using a static method MathKit.AngleBetweenPoints(p1, p2) which is pretty obvious, but for some reason the code did not produce the results I predicted, so I wrote a bit of code to ensure the output I was looking for.
The issue was that MathKit.AngleBetweenPoints(p1,p2) returns an angle in radians and I wanted degrees. I already have two static methods in the MathKit class to convert radians in degrees and vice-versa, so in the next refactoring session I’ll rename MathKit.AngleBetweenPoints to MathKit.RadiansBetweenPoints and create a new DegreesBetweenPoints.
The refactoring will eliminate generic code from game specific code, it will reuse static methods we already have in the MathKit class, make the method already there more intuitive and create an additional method for other uses.
Managers = Singletons
Managers are classes that take care of a specific aspect of your game. Scenes, music, sound and so on. You should be sure that your managers are singletons and that you can access them everywhere. To be sure of it, all our managers are loaded by the Application Manager which is what all our document classes extend. Neat trick and quite useful.
Tools = Static
All our tools are static methods. We don’t want our tools to be instantiated. We don’t want our tools to hold data. We want our tools to do something specific and produce an output.
At the end of the day
Like I said, when we start a new game I copy the core directory of the latest game to the new one. Usually I take a look a t it or look for //TODO remarks for something I want to review. While the code base was growing this was very useful, right now it’s a matter of tunning some details since most work is done while refactoring.
I do have a damn project to go though… writing the graphic handling classes… but I still have a load of doubts to sort first.
Oooops… big one… Vlad out!
Posted: June 30th, 2009
at 11:40pm by Vlad
Tagged with Bold Pixel Engine, Design Patterns, FlashGameBlogs
Categories: The code of VGS
Comments: 1 comment
