lua-users home
lua-l archive

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


David Lam wrote:
> 
> Basically I want to minimise the amount of temporary memory being allocated,
> so that I can reduce the frequency GC is called (and maybe reduce the hit of
> each GC?). Can anyone give some hints on this topic?
> 
> For instance, if I have local variables declared inside function A, will the
> local variables allocate memory each time A is called?

No.  Local variables are kept on a stack and will not effect the GC.

These constructs will create a new garbage collected object:

 - a..b  (example only; any string generating construct i.e. strsub() or
          lua_pushstring().)

   Each _new_ string creates a new object.  Lua has unique strings, that
   means that each possible string exists only once within Lua.  If a
   new string occurs Lua first checks if it already exists within the
   string pool.  If it does, a reference to that older string is used.
   If it does not exist, a new string object is created and put into the
   string pool.  The GC checks the string pool for unused strings and
   frees them.  So creating a lot of unique strings will trash the GC.
   I.e. this is bad GC-wise:

      for i=1,100 do  x="foo"..tostring(i)  end  -- 100 new strings

   Note: Code segments hold references to strings constants (a la "foo"
   above).  So the string will exist in the string pool as long as the
   function exists; it does _not_ has to be created each time the func-
   tion is executed.

 - { ... }

   Each time a table constructor is executed a new table is created.
   Try to reuse tables if possible.

 - function() ... end
   
   Executing a function statement creates a closure (note: not calling
   the function but executing the function statement!).  Normally no
   big impact on the GC but if you have function statements within a
   loop you may create a lot of garbage.  I.e.:

      for i=1,100 do  foo(function() end)  end  -- bad for GC

   creates 100 function closures.

 - function(foo, ...) end

   Vararg functions create a table for the ellipsis (stored in 'arg')
   each time the function is _called_.

 - userdata objects

   In Lua 4.0 (and 3.x) userdata objects are handled similar to strings.
   They are equal if the pointer value and the tag are equal.

 - dofile/dostring

   Well, these load/compile new code and will create strings and (GCed)
   code segments.

Ciao, ET.