Garbage collection (nothing to attract flames ;))

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Garbage collection (nothing to attract flames ;))

Adam D. Moss
Hello!

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?

I can see how this would be of some benefit for global
variables which would otherwise hang around indefinitely,
but what about short-lived local variables and the contents
of local tables, etc?

Thanks,
--Adam
--
Adam D. Moss   . ,,^^   [hidden email]   http://www.foxbox.org/   co:3
"Responsible parents don't raise kids in West Virginia."


Reply | Threaded
Open this post in threaded view
|

Re: Garbage collection (nothing to attract flames ;))

Steve Dekorte-4

On Thursday, June 12, 2003, at 10:20 AM, Adam D. Moss wrote:
I can see how this would be of some benefit for global
variables which would otherwise hang around indefinitely,
but what about short-lived local variables and the contents
of local tables, etc?

Since (I think) Lua uses a standard mark and sweep collector, this shouldn't effect collection unless a collection cycle kicks in while your function is being executed and even then, I can't see how it would have any noticeable effect unless a local you nilled out pointed to a large table structure or userdata containing a bunch of data.

Cheers,
Steve
Io, a small language: http://www.iolanguage.com/


Reply | Threaded
Open this post in threaded view
|

Re: Garbage collection (nothing to attract flames ;))

RLak-2
In reply to this post by Adam D. Moss
> 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