lua-users home
lua-l archive

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


One can build bucket brigades to keep things around longer based on GC cycles or based on total accumulated data. That said, the data in the cache isn't going away from memory until the GC actually gets around to collecting it which means that the weak table (if it worked) would always be a viable optimization provided you aren't worried about the file changing on disk.

The work around for the handling of strings in this case would be to have the values be tables containing the file contents as a string. Since these tables would never be referenced elsewhere they would not survive a GC pass. But then to make the above storage management ideas (bucket brigades, etc) work you do need to expose the tables, so it's not really a satisfactory solution.

Mark

On Oct 21, 2009, at 4:51 AM, Cheng, Long wrote:

From my opinion, implement a data cache using weak table is not a good idea. If you do so, your application will have no control over when the data in cache will be garbage collected. Even if the data is access very frequently by clients, it may still be collected immediately after all references are released. You should implement the cache in a regular table and implement a replacement algorithm to manage the data in cache.

Regards
Long

Mark Hamburg 写道:
I understand the theoretical arguments for treating strings as values with respect to weak tables, but are there any practical benefits? It would seem, for example, to get in the way of caching the results of file reads a la:

fileCache = setmetatable( { }, {
__mode = 'kv',
__index = function( t, k )
local v
local f = io.open( k )
if f then
v = f:read( "*a" )
t[ k ] = v
f:close()
end
return v
end } )

Mark