Memory
Pool
Reuse objects instead of creating and destroying them, for bullets, effects, UI rows and anything spawned often.
PackageShared
Getting it
local Pool = Engine:GetPackage("Pool")Overview
Creating Instances is expensive, and destroying them creates work for the garbage collector. A pool keeps finished objects around and hands them out again. You take an item with :Get(), and give it back with :Return() when you are done instead of destroying it.
A bullet pool
local Pool = Engine:GetPackage("Pool")
local bullets = Pool.new({
create = function()
local bullet = bulletTemplate:Clone()
bullet.Parent = workspace.Bullets
return bullet
end,
reset = function(bullet)
bullet.CFrame = CFrame.new(0, -1000, 0) -- park it out of sight
end,
destroy = function(bullet)
bullet:Destroy()
end,
initial = 50,
max = 200,
})
local function fire(origin: CFrame)
local bullet = bullets:Get()
bullet.CFrame = origin
task.delay(2, function()
bullets:Return(bullet)
end)
endMoving a part far away is much cheaper than changing its Parent, which is why the reset above parks bullets instead of removing them from the workspace.
Constructor
new
Pool.new(config: PoolConfig): Pool| Field | Description |
|---|---|
create: () -> any | Makes a new item. Required. |
reset: ((item) -> ())? | Prepares a returned item for its next use. |
destroy: ((item) -> ())? | Gets rid of an item the pool no longer keeps. |
validate: ((item) -> boolean)? | Checked on :Get(); items that fail (for example a part that was destroyed elsewhere) are thrown away and the next one is tried. |
initial: number? | Items to create up front. |
max: number? | Most idle items to keep. Items returned beyond this are destroyed. |
Members
| Member | Description |
|---|---|
:Get(): any | An idle item, or a new one if none is idle. |
:Return(item) | Gives an item back. Errors when the item is not checked out from this pool, which catches double returns. |
:Prewarm(count): number | Creates idle items ahead of time (up to Max) and returns how many were made. |
:IsInUse(item): boolean | Whether the item is checked out. |
:Clear() | Destroys every idle item. Checked-out items are untouched. |
:Destroy() | Clears the pool and stops it. Items returned later are destroyed straight away. |
Size, FreeCount, InUseCount | Totals, idle and checked out. |
Max, Destroyed | Settings and state. |
ItemCreated: Signal<item>, ItemDestroyed: Signal<item> | Fire when the pool creates or destroys an item. |
Configuration
Defaults from
DefaultConfiguration/Packages/Pool2 settings| Setting | Default | What it does |
|---|---|---|
| DefaultInitial | 0 | Items Pool.new() prewarms when config.initial is omitted. |
| DefaultMax | 256 | Idle items a pool keeps on hand when config.max is omitted. |
Types
export type PoolConfig
export type Pool