Simple Object Pooling in Flash

Been loving 360 Flex this year! Tyler and I finally finished our presentation, and so I had some time to write a post I’ve been meaning to.

One of the issues one comes across in building performant applications in Flash is object creation and garbage collection. Object pooling helps overcome this. Object pooling is keeping old objects around and reusing them instead of throwing them away and always creating new fresh objects.

Creating objects in Flash isn’t bad. It’s when you create hundreds or thousands of throw-away objects very quickly that this becomes a problem.

Used Pooling in Observe

For my final implementation of the Observe class I use objects to temporarily store information about hooks and observers that allows me to sort them based on order they were added. At first I thought how unfortunate that I have to create objects to do this when one of the major reasons for creating Observe is to eliminate the creation of Event objects every time a property change happens.

Fortunately I have complete control over Observe and its implementation (unlike Flash’s Event model) and I can pool these temporary objects. Setting up pooling is very simple and I’d like to demonstrate how it can be done by pretending we’re building a super-fast memory efficient best-performance tween engine. We’ll go with this use case, build pooling, and let the remainder of the tween engine be left to the imagination or as an exercise of the reader to finish.

Tweening Ultra-Speed

Our pretend tween engine is called Tweening Ultra-Speed, because that sounds super cool. Super duper cool (k, so it’s late). The biggest problem with high-peformance tween engines like GreenSock’s preventing them from pushing beyond their top speeds even further is object creation and garbage-collection. In order to create a new tween the API might look like this:

Tween.create({target: mySprite, duration: 1000, x: 10, y: 20});

No big deal, right? Unless you’re pushing the limits and creating thousands of these every second. The object being created between those parentheses is being allocated some memory and then garbage collected later. Memory builds up as thousands of these are called, then drops back down (with a noticeable pause in the animation) because the garbage collection cleans up the old objects.

How else could we do this?

We need to have objects that we can reuse. We might go specific and have a MovementTween that holds the x/y properties. We might do a size tween that holds the width/height properties. I’m going to go with generic and do a property tween for each type of property. For now, we will cover 90% + of tween use-cases with a NumberTween object.

public final class NumberTween
{
	public var name:String;
	public var value:Number;
	
	public function NumberTween(name:String, value:Number)
	{
		this.name = name;
		this.value = value;
	}
}

I’m keeping it simple and not including other stuff we might need such as current value and delta value, easing, and stuff like that. Now we have a concrete object that would be used like so:

var tween:Tween = new Tween(mySprite, 1000); // let's say 1000 is the duration
tween.addProperty(new NumberTween("x", 10));
tween.addProperty(new NumberTween("y", 20));

Of course, this doesn’t solve the problem yet, but now that we have a concrete class, we can make a pool for NumberTweens. My favorite way is to add a static method on the class and using a link-list. It is very fast and light, and I think very elegant.

public final class NumberTween
{
	public var name:String;
	public var value:Number;
	public var next:NumberTween; // this is for the link-list. We can also use this outside the pool to link our tweens together in the addProperty calls.
	
	private static var pool:NumberTween;
	
	public static function get(name:String, value:Number):NumberTween
	{
		var tween:NumberTween = pool;
		if (tween == null) tween = new NumberTween();
		
		pool = tween.next;
		tween.next = null;
		tween.name = name;
		tween.value = value;
	}
	
	public static function put(tween:NumberTween):void
	{
		tween.next = pool;
		pool = tween.next;
	}
}

The important things to note here are the static get and put methods. You now use get to retrieve a new NumberTween instance and put to “release” it back to the pool once you’re done with it. If your pooled object points to any objects or non-mutable types (non-string/number/boolean) this could be where it gets cleaned up too (don’t keep mySprite tied in memory to a pooled Tween object). I’ve also made a method called destroy that does the same thing, puts it back into the pool. Let’s say we do something similar for our Tween class as well.

var tween:Tween = Tween.get(mySprite, 1000);
tween.addProperty(NumberTween.get("x", 10));
tween.addProperty(NumberTween.get("y", 20));

Once the tween has finished running it can call a Tween.put() on itself which might call property.constructor.put() on all of its properties. The great part for this particular scenario is that you can have NumberTween, ColorTween, BlurFilterTween, etc. for each type you want to support! Now we may be creating thousands of tweens every second but we’re recycling object instances so that object creation is limited and garbage collection isn’t slowing things down. What is it they say? “Reduce, reuse, recycle.”

This is my take on object pooling. You could create a pooling framework, but it is so simple to add pooling to a class, it doesn’t seem necessary for quick things. And this pooling would speed up tween engines that much more (at the expense of more lines of code to create a tween. There are trade-offs).

So who’s going to finish my tween engine for me?

ooCommerce Help

We are calling for developers who would like to join in on a fun object oriented PHP 5 ecommerce project entitle ooCommerce. Please email me or leave a comment if you would like to be a developer on this project or help in any way. The project is hosted at SourceForge and currently only has downloads for the template system it will be using, Arras Template. Arras Template has a website at www.arrastemplate.org. We (actually just myself right now) hope for this to be a good learning experience for others and are blogging about our design decisions how we are putting it together along the way. This way it can be more of a case study in progress for others to learn in a more of hands-on way about object oriented programming. Anyone is invited to help out, whether they know object oriented programming or not. If OOP isn’t a strong point, then you can just help coding (with guidance if desired). If it is a strong point, then you can help in the design process as well and post some blog posts too. I can do the design, database, classes, and all, but it would be a better project with more minds at work on it. It will also be finished sometime this century. Thank you for your help.

ooCommerce – A Deeper Look, More Decisions

We’ve broken down our system down into some general parts already. Now it’s time to make some decisions on more specific pieces of ooCommerce and break the system down into some main objects.

What’s in our Model

Well, first off, we know we need a database to store all of our store’s data. We’ll put off the database schema for now. But what we do need to decide is what database to use. And if we want to support several databases (which we do), what should we do to abstract the databases so that we use the same API no matter which database we use.

There are a few object-oriented options out there. My favorite is Creole, a PHP 5 database abstraction layer which has a nice interface. There is also PEAR’s DB which I’ve actually never used and have heard good things about. The good things about these are that they’re already built and they are actively developed which means others are fixing the bugs and adding features so we don’t have to. However, they are large, and the API of Creole is more of what Java programmers are use to and not what PHP developers are use to. We could also create our own object oriented abstraction layer. It would be smaller and use the API we want. Much more simple code. What do you think we should do?

The rest of the model would include the following list of objects, plus maybe a few we havn’t thought of yet:

  • Customer
  • Address Book
  • Address
  • Payment (stored)
  • CustomerGroup
  • Order
  • OrderItem
  • PaymentMethod
  • DeliveryMethod
  • Product
  • ProductReview
  • ProductSpecial
  • Catalog
  • Category
  • ShoppingCart
  • Translator
  • Pages
  • Content
  • Administrator
  • Report

There of course will need to be an object type for each method of payment and other additions like that. But I think we’ve got a pretty good layout here. We may think of other things later, especially when we want to add features.

How Will We Control Our Model

The controller part of our system could be pretty simple, or pretty elaborate. It all depends on what we value the most. If we like simple the best, we can just have a bunch of PHP pages that our use will go to, they will run the code they need to run, using the model objects, and then they will pull in a template and output the results. The URLs for these will be the name of the files, plus any parameters passed in the URL. These will be pretty procedural, although we could make them into classes to keep it object oriented. Another option is to push for search engine optimization by building our system with URLs that represent the page being displayed. If we go simple, we will have a “product.php?id=10” or “product.php?name=james_bond_movie” displaying our products. If we choose the more complex controller we would have “products/james_bond_movie” be our URL, which ranks it higher on the search engines. To do this we would need to use mod_rewrite with Apache and set up our scripts to handle these URLs. But it is very do-able. Do we want full-featured, or do we want simplicity? The value of ooCommerce will be higher with better features to it’s users.

Gotta See The View

There are a million and one template systems out there (I wrote the 1,000,001 template system) and most very similar. Smarty is the most popular it seems. And most are similar to Smarty except less features or slower. I happen to be partial to my templating system, Arras, which is different from most. It is also fast, and small, and fun to use, and easy for designers to do design on. So, I would like to use Arras.

So, what are your thoughts? Please give feedback on the following design decisions. We would love to get input.

  • What database abstraction layer should we use?
  • Any additional classes I forgot in the model?
  • Go for a simpler controller, or nicer URLs?
  • Use Arras for the template system or something else?

ooCommerce – The Overall Picture

So, we’re going to build ooCommerce, an ecommerce solution, an open source one. What pieces are involved? What are the major components of the system? Let’s get this organized using a top down approach.

Every ecommerce system has a few major parts in common. One is the catalog. This is where we can browse and search for the products. Then, we have the shopping cart. This is where we put the products when we want to buy them. We have our checkout, which is the process where we can purchase what is in our shopping cart. And lastly, many systems including ours will have a customer account section, where we can view our past orders and get support. Actually, we are fogetting a major part of the system. The administrative section. This can sometimes be the largest section and will help us organize the catalog, oversee orders, configure the system, and all the other administrative tasks associated with running an ecommerce store. Here are the “main sections.”

Main Ecommerce Sections

We will be storing many of the store’s information in a database. So we will need a database package (when I say package, it might be one class or a group of classes, we can figure out which later). We also want to keep the HTML and style of the site seperate from the code as much as possible so that it can change. This is a very important piece that osCommerce has not done well in. It can be very difficult to reskin osCommerce. So we will have a template package. We want to model an actual store in our code for a simpler and easier to code/understand system. This part will be the model and will be the one to interact with the database. Finally, we need something that takes the pages or actions of our store user, puts together the model information and the templates, and gives it back to our user. This will be our controller. So, we have a model, view, controller system we will be making. It will give us greater flexability. Here are the “MVC sections.”

Model View Controller Sections

The MVC (model, view, controller) sections aren’t different from the main sections described above. Rather, they are another way of looking at our system. We will have a customer class (from the model) used in the admin section, the shopping cart section, the order section, and the customer account section. The main sections above indicate the sections of the website, and the MVC sections indicate the different layers of code we will use in the website.

Right now we haven’t gotten to our classes yet. We’ve just been breaking the system up into smaller pieces. These may be organized into folders of classes or they may just be for our own reference.

We have successfully broken down the system one level. We will look at breaking down the system into small parts next time. We are on our way to a successful ecommerce solution.

Tutorial? How About a Project!

In writing the articles on object oriented programming I have stuck with theory. After all, it is not language specific and takes less space to say what there is to say. However, I have been asked by serveral to provide a tutorial or include examples on object oriented code. Well, I’ve decided to do something more. My good friend Andrew Branch has pointed out many times before that we learn better when we do things ourselves. And so, in that spirit, we will start a new full-fledged project together. I will write along as we develope it about how we should try to do things, so we can more fully understand object oriented principles. And we can all write the code for it.

The Project

Going back to my roots, I learned to program by hacking on osCommerce code. I wanted to make my own ecommerce site and run my own buisness. It was then that I discovered how enjoyable programming was and stuck with that instead. The problem with osCommerce is, however, that it is very procedural. It has SQL queries inline with the HTML on it’s pages. It uses functions to output pixel images. It requires a lot of hacking to modify. It is an adequate example of what you might call “spaghetti code.”

ooCommerce

We will be starting a new open source project that will implement all the features of osCommerce, but in a better way. And hopefully, since this will be more extensable, we can add many new features. We can call this project ooCommerce for object oriented ecommerce. I have already purchased the domains oocomerce.com, .net, and .org so that we may, eventually, have our own site for it. And I have submitted it to Sourceforge for pending approval. The benchmark of features we will be aiming for is listed on osCommerce’s site. And, because we are going full out object oriented, we will be using PHP 5. I am sorry if you were hoping for PHP 4, but in order to teach better OOP principles, and because PHP 4 is such a hack in terms of OOP, that’s what we need to use.

I hope ooCommerce will be, if nothing else, a great learning experience. Instead of a little pointless tutorial on saying “hello world” in an object oriented manner, we will actually create a full-featured system as our tutorial, implementing all that we’ve learned previously. We will look at planning this project out next week, so stay tuned.

PHP Package Management and Autoloading

In PHP 5 and greater there is a magic function called __autoload (note: two underscores). __autoload allows us to load a class on the fly so to speak. It only gets called when a class can not be found, then it has a chance to load the class. If the class still can not be found, you get your regular error stating so. __autoload can be really useful if all of your classes happen to be in one directory, but what happens if you are managing a large project with many packages of classes? We will look at some different options.

Single Directory of Classes

This is the simplest solution, and the best if you have a small project. You may have situations where you would like to load the class without creating a new instance of it, so I will be creating a loadClass function in each example which __autoload will call. That way you may load a class manually. Here is what you might do if all of your classes are in one directory:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    include_once('classes/' . $className . '.php');
}

Pretty Simple.

Packages of Classes

Now how about package management, with many directories of classes? A few developers have named their classes with the package names in the class name. For example, util_Parser would be the Parser class in the util directory (in your base classes directory), and util_html_HTMLParser would be the HTML parser class in the util.html package. Here is an example of how that would work:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    include_once('classes/' . str_replace('_', '/', $className) . '.php');
}

Simple like the first method, but we get packages now. However, we have to actually name our classes with the package names in front of it. We start to get very long names for some of our classes. If we extended the Parser class we might have util_html_HTMLParser and util_xml_XMLParser or perhaps even deeper packages. We also find refactoring difficult because if a class must move to another package, we must go through all our code and rename the class everywhere we use it.

Package Management Using import

There is another way, although not as simple, which allows packages as deep as you would like, and requires minimal work when refactoring. This is the import way of doing things. import is a function which keeps track of what classes you might use in a certain script/class and then uses __autoload to look up the location of the class. Here’s how it works.

  • You import the class or package using the import function like this, import('util.html.HTMLParser');, at the top of your script
  • import stores the name of the class, ‘HTMLParser’, and the path to the class, ‘util/html/HTMLParser.php’, in a global associative array called imports
  • When the class is utilized, __autoload will do a lookup in the imports array for the class and load it in.

Here is how the code looks. It is a bit more complicated, but very nice to use for a larger system:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    global $imports;
    if (isset($imports[$className])) {
        include_once($imports[$className]);
    }
}

$imports = array();
function import($import) {
    global $imports;

    // seperate import into a package and a class
    $lastDot = strrpos($import, '.');
    $class = $lastDot ? substr($import, $lastDot + 1) : $import;
    $package = substr($import, 0, $lastDot);

    // if this import has already happened, return true
    if (isset($imports[$class]) || isset($imports[$package.'.*'])) return true;

    // create a folder path out of the package name
    $folder = '' . ($package ? str_replace('.', '/', $package) : '');
    $file = "$folder/$class.php";

    // make sure the folder exists
    if (!file_exists($folder)) {
        $back = debug_backtrace();
        return trigger_error("There is no such package <strong>'$package'</strong> -- Checked folder <strong>'$folder'</strong><br />
            Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
    } elseif ($class != '*' && !file_exists($file)) {
        $back = debug_backtrace();
        return trigger_error("There is no such Class <strong>'$import'</strong> -- Checked for file <strong>'$file'</strong><br />
            Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
    }

    if ($class != '*') {
        // add the class and it's file location to the imports array
        $imports[$class] = $file;
    } else {
        // add all the classes from this package and their file location to the imports array
        // first log the fact that this whole package was alread imported
        $imports["$package.*"] = 1;
        $dir = opendir($folder);
        while (($file = readdir($dir)) !== false) {
            if (strrpos($file, '.php')) {
                $class = str_replace('.php', '', $file);
                // put it in the import array!
                $imports[$class] = "$folder/$file";
            }
        }
    }
}

There you have it. A powerful way to manage your packages and load only classes which are needed for use. Also, a feature of this method of autoloading classes is that you can use an asterisk, *, to import all the classes in a package. And it only loads the classes needed because of __autoload.

Finally, this is how you would use the import method in your scripts:

import('util.html.HTMLParser');
import('template.arras.*');

// here would be all of your important code
// not worrying about including files hwen you need them
// because you've already set it up to include them
// automatically when you use them, and only
// _if_ you use them
$p = new HTMLParser();
$t = new ArrasTemplate();
// etc.
Next Page »