lua-users home
lua-l archive

Re: Minimising memory allocation

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


| 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?
This is my understanding of what happens (so I'd like to know if I'm wrong
because I've only poked around in the Lua source a bit :-)
It depends on what type is declared. If you declare a number value then this
just goes on the stack (all of the value types are a union, with number being a
float/double and the rest being pointers to data). Everything else creates an
object which must be collected later. Have a look at lvm.c and see the script i
wrote to merge source code and vm code:
http://groups.yahoo.com/group/lua-l/message/4931 (mail me for code if
necessary) - eg. look what happens when you create a local table.
Its good to make commonly used (especially none number) information global, or
encapsulate related information in a class/table to avoid creating and
collecting them constantly. ie. if you maintain a reference to them they are not
collected (and dont need to be recreated either).
Reuse objects: eg.
function new_matrix() return { 0,0,0,0 } end
function set_identity(m) m[0],m[1],m[2],m[3] = 1,0,0,1 end
function set_identity2(m) return {1,0,0,1} end
m = new_matrix()
set_identity(m)
-- rather than
m = set_identity2()
function <2:@b.lua> (17 instructions/68 bytes at 002F3328)
1 param, 13 stacks, 1 local, 0 strings, 0 numbers, 0 functions, 3 lines
 1 [2] GETLOCAL 0 ; m
 2 [2] PUSHINT 0
 3 [2] GETLOCAL 0 ; m
 4 [2] PUSHINT 1
 5 [2] GETLOCAL 0 ; m
 6 [2] PUSHINT 2
 7 [2] GETLOCAL 0 ; m
 8 [2] PUSHINT 3
 9 [2] PUSHINT 1
 10 [2] PUSHINT 0
 11 [2] PUSHINT 0
 12 [2] PUSHINT 1
 13 [2] SETTABLE 6 1
 14 [2] SETTABLE 7 1
 15 [2] SETTABLE 8 1
 16 [2] SETTABLE 9 9
 17 [2] END
function <3:@b.lua> (8 instructions/32 bytes at 002F34A0)
1 param, 6 stacks, 1 local, 0 strings, 0 numbers, 0 functions, 3 lines
 1 [3] CREATETABLE 4
 2 [3] PUSHINT 1
 3 [3] PUSHINT 0
 4 [3] PUSHINT 0
 5 [3] PUSHINT 1
 6 [3] SETLIST 0 4
 7 [3] RETURN 1
 8 [3] END
Lunchtime: down tools. Thats all I can think of for now.
N

AltStyle によって変換されたページ (->オリジナル) /