lua-users home
lua-l archive

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


> If you do not want to waste memory and slow down GC with proxies to 
objects
> that exist long but are seldom used in Lua code, you should also make 
the
> table weak and recreate a proxy whenever one is needed and does not 
exist
> in the cache table.

That probably will not have as much benefit as you might think. First of 
all,
weak tables do not generally shrink. Secondly, garbage-collecting a weak
table is probably slower than garbage-collecting a regular table, even
though it is not necessary to do as much marking, because the table needs
to be rescanned for deleted elements (even if there aren't any).

A boxed pointer occupies relatively little space (although if you had 
thousands
of these, it would be irritating) and a userdata has only one reference
(the metatable), so it takes little time to mark it.

The one reason you might want to use a weak table is to know when there 
are
no longer Lua references to the proxy; in that case, you could assign a
finalisation (__gc) method to the proxy object which, perhaps, decremented
a reference count. But that was not the question being posed :)
 
>> Also, you do not technically need a separate
>> table; you can simply use the registry as long as you follow the
>> convention (followed by the Lua libraries) that a lightuserdata used as 
a
>> key in the registry is always the address of allocated storage.

> But can't this (in theory at least) conflict with the reference system?

No. The reference system uses numbers as keys. lightuserdata are freely 
usable as long as you maintain the convention that any lightuserdata used 
as a registry key is a pointer to allocated storage. The number 27 and the 
lightuserdata containing the internal value 27 are not the same Lua 
object.

Using lightuserdata which contained small integers would not be a good 
idea -- you would have no way of knowing that the small integers you were 
using didn't conflict with small integers some other (imaginary) library 
used. But if every library uses pointers to storage which it itself has 
allocated (or which is a static internal object), no conflicts will arise.

Like numbers, lightuserdata do not impose any marking overhead on garbage 
collection, by the way. So they're a good choice for this application.