2021-07-15 06:09:08 +00:00
|
|
|
--[[
|
|
|
|
add pooling functionality to a class
|
|
|
|
|
2021-07-15 06:15:58 +00:00
|
|
|
adds a handful of class and instance methods to do with pooling
|
2021-10-19 04:41:40 +00:00
|
|
|
|
|
|
|
todo: automatically use the pool by replacing __call, so you really just need to :release()
|
2021-07-15 06:09:08 +00:00
|
|
|
]]
|
|
|
|
|
|
|
|
return function(class, limit)
|
|
|
|
--shared pooled storage
|
|
|
|
local _pool = {}
|
|
|
|
--size limit for tuning memory upper bound
|
|
|
|
local _pool_limit = limit or 128
|
|
|
|
|
|
|
|
--flush the entire pool
|
|
|
|
function class:flush_pool()
|
|
|
|
if #_pool > 0 then
|
|
|
|
_pool = {}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
--drain one element from the pool, if it exists
|
|
|
|
function class:drain_pool()
|
|
|
|
if #_pool > 0 then
|
|
|
|
return table.remove(_pool)
|
|
|
|
end
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
|
|
|
--get a pooled object
|
|
|
|
--(re-initialised with new, or freshly constructed if the pool was empty)
|
|
|
|
function class:pooled(...)
|
2024-11-01 00:27:27 +00:00
|
|
|
local instance = class:drain_pool()
|
|
|
|
if not instance then
|
2021-07-15 06:15:58 +00:00
|
|
|
return class(...)
|
2021-07-15 06:09:08 +00:00
|
|
|
end
|
2021-07-15 06:15:58 +00:00
|
|
|
instance:new(...)
|
|
|
|
return instance
|
2021-07-15 06:09:08 +00:00
|
|
|
end
|
|
|
|
|
2021-08-13 00:56:53 +00:00
|
|
|
--release an object back to the pool
|
2021-07-15 06:09:08 +00:00
|
|
|
function class:release()
|
|
|
|
if #_pool < _pool_limit then
|
|
|
|
table.insert(_pool, self)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|