본문 바로가기

액션스크립트 3.0

메모리최적화 : 풀링기법


객체풀링

시간 경과에 따라 객체를 다시 사용하는 것과 관련된 객체 풀링 기술.

- 객체풀링 베이스 클레스
package
{
     import flash.display.Sprite;
     public final class SpritePool
     {
          private static var MAX_VALUE:uint;
          private static var GROWTH_VALUE:uint;
          private static var counter:uint;
          private static var pool:Vector.<Sprite>;
          private static var currentSprite:Sprite;

          public static function initialize( maxPoolSize:uint, growthValue:uint ):void
          {
               MAX_VALUE = maxPoolSize;
               GROWTH_VALUE = growthValue;
               counter = maxPoolSize;
               var i:uint = maxPoolSize;

               pool = new Vector.<Sprite>(MAX_VALUE);
               while( --i > -1 )
                    pool[i] = new Sprite();
          }
          public static function getSprite():Sprite
          {
               if ( counter > 0 )
                    return currentSprite = pool[--counter];

               var i:uint = GROWTH_VALUE;
               while( --i > -1 )
               pool.unshift ( new Sprite() );
               counter = GROWTH_VALUE;
               return getSprite();
          }
          public static function disposeSprite(disposedSprite:Sprite):void
          {
               pool[counter++] = disposedSprite;
          }
     }
}

- 사용예제
const MAX_SPRITES:uint = 100;
const GROWTH_VALUE:uint = MAX_SPRITES >> 1;
const MAX_NUM:uint = 10;

SpritePool.initialize ( MAX_SPRITES, GROWTH_VALUE );

var currentSprite:Sprite;
var container:Sprite = SpritePool.getSprite();
addChild ( container );

for ( var i:int = 0; i< MAX_NUM; i++ )
{
     for ( var j:int = 0; j< MAX_NUM; j++ )
     {
          currentSprite = SpritePool.getSprite();
          currentSprite.graphics.beginFill ( 0x990000 );
          currentSprite.graphics.drawCircle ( 10, 10, 10 );
          currentSprite.x = j * (currentSprite.width + 5);
          currentSprite.y = i * (currentSprite.width + 5);
          container.addChild ( currentSprite );
     }
}

stage.addEventListener ( MouseEvent.CLICK, removeDots );
function removeDots ( e:MouseEvent ):void
{
     while (container.numChildren > 0 )
     SpritePool.disposeSprite (container.removeChildAt(0) as Sprite );
}