Monkey Documentation

Class Pool<T>

A pool object allows you to manually allocate and free objects from a memory pool. More...


Constructors:
  • New ( initialCapacity:Int=10 )
Methods:

Detailed Discussion

A pool object allows you to manually allocate and free objects from a memory pool.

A pool can be used instead of New in situations where you want to minimize garbage collection.

Example

Import brl.pool

Class Actor

    Function Create:Actorx:Float,y:Float )
        Return _pool.Allocate().Initx,y )
    End
    
    Method Destroy:Void()
        _pool.FreeSelf )
    End
    
    Method IsDead:Bool()
        Return _t=0     'timeout?
    End
    
    Method Update:Void()
        If _t>0 _t-=1   'update timeout
    End
    
    Private
    
    Field _x:Float
    Field _y:Float
    Field _t:Int
    
    Global _pool:=New Pool<Actor>( 1000 )
    
    Method Init:Actorx:Float,y:Float )
        _x=x
        _y=y
        _t=Rnd(20,100)  'random timeout
        Return Self
    End
    
End

Function UpdateActors:Voidactors:Stack<Actor> )

    'Update all actors
    For Local i:=0 Until actors.Length
        actors.Get(i).Update()
    Next
    
    'Flush dead actors, compacting stack as we go...
    Local alive:=0
    For Local i:=0 Until actors.Length
        Local actor:=actors.Geti )
        
        If actor.IsDead() 
            Print "Dead!"
            actor.Destroy()
            Continue
        Endif
        
        actors.Set alive,actor
        alive+=1
    End
    
    actors.Length=alive     'v70 only...

End

Function Main()

    Local actors:=New Stack<Actor>
    
    For Local i:=0 Until 100
        actors.Push Actor.CreateRnd(100),Rnd(100) )
    End
    
    While actors.Length
        UpdateActors actors
    Wend
    
    Print "Done!"

End


Constructor Documentation

Method New ( initialCapacity:Int=10 )

Creates a pool containing initialCapacity objects.


Method Documentation

Method Allocate : T ()

Allocates an object from the pool.

If the pool is empty, an object created using New is returned instead.

Method Free : Void ( t:T )

Adds an object to the pool. This object is then available for future use by Allocate.