Monday, April 19, 2010

AS3 memory management part II

I went through and did the plan from my previous AS3 memory management post and things are looking better. By just allocating things one time at the beginning of the game and pushing them to the display list once as well, I'm now at about 1/2 the amount of memory hogged by the time I reach level 20 of the game.

This should be sufficient to solve the problem of game slowdowns.

At this point I could pull all of the frames and such from the game, but I don't think I'm going to do that. If a person runs back and forth in the menu and such 100x, it'll likely bump up the memory usage a bit but not nearly as badly as the game frame is and it's frankly an edge-case anyway.

The bottom line is that if you're coding up a game or application that has a number of levels to it, and is full of tons of graphical elements and such, you'll probably want to:
  • Do all of your allocation at the start of your game
  • Use addChild(...) as you allocate and then just write a little function that "hides" your graphics by altering their x and y to be something like: -999,-999
  • Show your graphics by setting the new x and y to wherever they should actually be
  • Make sure you don't undercut the number of graphics you'll need when doing your initial allocation
Now before anyone gets all fired up about the use of globals here. You don't have to use globals. You can create a class that handles all this stuff and encapsulates things neatly. It'll add a little overhead doing this, but for purists it should work fine. For everyone else, globals are not as neat and tidy, no, but they do give that feeling of old-skool hack development. :)

2 comments:

  1. Aw, I was expecting some sample code to go along with this entry. Seems like a good solution to a bad GC though.

    ReplyDelete
  2. Not really sure what code I would put on it. It's more of a methodology than a code point, but here is a little something (hopefully it's not buggy...I'm winging it real quick here):

    var piece:Piece;
    var pieces:Array = new Array(81);
    for(i=0;i<80; i++)
    {
    piece = new Piece();
    piece.x = -999;
    piece.y = -999;
    piece.gotoAndStop(1);
    addChild(piece);
    pieces[i] = piece;
    }

    ..then you can just up the pieces[i].x and pieces[i].y to set the placement and such, and you shouldn't ever have to use removeChild(...) on these. This avoids all the adds and removes from the display list.

    ReplyDelete