lua-users home
lua-l archive

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


> I was wondering, since I've seen this done occasionally while
> browsing other peoples' code: does it in any real way aid garbage
> collection (either in terms of immediacy of collection or
> gc running time) to explicitly nil-out variables which you
> know you won't be accessing again?

If you know you won't be accessing them again, try to put
them into a local block:

do 
  local f1, f2, fibonacci = 1, 1, {1, 1}
  for i = 3, 100000 do
    f1, f2 = f2, f2 + f1
    fibonacci[i] = f2
  end
  -- some computation with fibonacci
end
-- poof!

Not only does this avoid hanging on to garbage, it also avoids
polluting your namespace and using more stack slots than necessary.
It is faster and cleaner than setting variables to nil.

Note that garbage collection only happens after Lua does an
allocation. Most malloc implementations don't restore unused
memory to the system anyway, so this only matters if you have
some C component which is also memory hungry. If you do, watch
out for this situation (folowing on from the previous example):

-- poof!
-- maybe you want to explicitly collect garbage here
for i = 1, 100000 do
  some_cfunction(i)
end