lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Is there a way to cache/re-use tables automatically behind the scenes?

 

This is what I want to do:

 

function foo()

    local t = ObjectFactory() – This function returns tables (from a pool of reusable tables, or new table if pool is empty)

    …

    -- use ‘t’

    …

-- When ‘t’ goes out of scope, (i.e. no more refs to it) I want it to automatically be added back into the pool for re-use.

-- ‘t’ may be passed to other functions (or returned from this function), so I can’t just place it back into the cache manually at the end of this function.

end

 

I was hoping that when someone wants a “new” object, I could remove it from the pool of unused objects, and add it to a table of weak references to “used” objects before I give it to the user.

If there was a way for me to be notified when the object has no more strong refs to it, I could move it back into the pool (before its actually garbage collected).  It seems that I can’t use __gc to do this, since that only gets called for userdata (not tables), and may be too late.

 

The problem I’m trying to solve is that the programmers on this project have written lots of code that is constantly creating way too many temporary objects, which bogs down the memory manager (causes low frame rates, and choppiness).

 

I would like to solve this problem automatically in one spot, at all possible (auto cache these objects, and reuse them), so that we don’t have to modify all the places that cause this.

 

I’m thinking that maybe this can’t be done.  Perhaps there would be too many side effects to resurrecting the object.

 

Thanks.

 

Brian