lua-users home
lua-l archive

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


On 23 September 2011 21:40, Michael Gerbracht <smartmails@arcor.de> wrote:
> Hello,
>
> I have a question regarding tables and garbage collection / memory saving. (I
> don't know whether it's relevant but I am using lua 5.1):
>
> As far as I know, when I create some tables:
>
> TableA = {<many entries>}
> TableB = {<many entries>}
> TableC = {<many entries>}
>
> and I delete one table:
>
> TableB = nil
>
> then lua will free (garbage collect) the memory that was used by TableB.
>
> If I put everything into one table and try the same:
>
> TableMain = {}
> TableMain.A = {<many entries>}
> TableMain.B = {<many entries>}
> TableMain.C = {<many entries>}
>
> TableMain.B = nil
>
> then the memory is not garbage collected by lua. I hope this is correct so
> far.
>

I think you are confusing garbage collection with the shrinking of tables. They are unrelated. An object (such as a table) is collected when there are no references to it. Your large table will be collected when you replace it with nil, regardless of whether it was in a variable or a table.

A table is a set of key->value pairs. Imagine TableMain like this:

 | "A" | TableA |
 | "B" | TableB |
 | "C" | TableC |


When you do TableMain.B = nil, TableB is garbage collected as there are no longer any references to it. But the table slot it occupied remains in memory internally:


 | "A" | TableA |
 |     |        |
 | "C" | TableC |


Table slots are only removed when the table is resized (which only happens when you add new keys), not as part of garbage collection.

Global variables are also stored in a table (_G by default), so the same applies to those too. Local variables likewise take up a stack slot in memory, whether they contain a reference to a table or nil.

In summary, don't worry about it. The space used by unrecovered table slots is negligible and rarely worth worrying about. Your actual data will always be garbage collected when not accessible.

Regards,
Matthew (hoping [probably in vain] that Gmail does the right thing with HTML emails)