lua - Globals are bad, does this increase performance in any way? -
lua - Globals are bad, does this increase performance in any way? -
i'm working in luajit , have libraries , whatnot stored within "foo", this:
foo = {}; -- global variable foo.print = {}; foo.print.say = function(msg) print(msg) end; foo.print.say("test") now wondering, using metatables , keeping libraries local help @ all? or not matter. thought of this:
foo = {}; local libraries = {}; setmetatable(foo, { __index = function(t, key) homecoming libraries[key]; end }); -- function create new library. function foo.newlibrary(name) libraries[name] = {}; homecoming libraries[name]; end; local printlib = foo.newlibrary("print"); printlib.say = function(msg) print(msg) end; -- other file: foo.print.say("test") i don't have tools benchmark right now, keeping actual contents of libraries in local table increment performance @ all? slightest?
i hope made mysef clear on this, want know is: performance-wise sec method better?
if link/give detailed explaination on how global variables processed in lua explain great too.
don't have tools benchmark right now
sure do.
local start = os.clock() i=1,100000 -- adjust iterations taste -- thing want test end print(os.clock() - start) with performance, pretty much want benchmark.
would keeping actual contents of libraries in local table increment performance @ all?
compared first version of code? theoretically no.
your first illustration (stripping out unnecessary cruft):
foo = {} foo.print = {} function foo.print.say(msg) print(msg) end to print function requires 3 table lookups:
index _env "foo" indexfoo table "print" index foo.print table "say". your sec example:
local libraries = {} libraries.print = {} function libraries.print.say(msg) print(msg) end foo = {} setmetatable(foo, { __index = function(t, key) homecoming libraries[key]; end }); to print function requires 5 table lookups along other additional work:
index _env "foo" indexfoo table "print" lua finds result nil, checks see if foo has metatable, finds one index metatable "__index" check see if result is table or function, lua find it's function calls key index libraries "print" index print table "say" some of work done in c code, it's going faster if implemented in lua, it's going take more time.
benchmarking using loop showed above, first version twice fast sec in vanilla lua. in luajit, both same speed. difference gets optimized away @ runtime in luajit (which pretty impressive). goes show how of import benchmarking is.
side note: lua allows supply table __index, result in lookup equivalent code:
setmetatable(foo, { __index = function(t, key) homecoming libraries[key] end } ) so write:
setmetatable(foo, { __index = libraries }) this happens lot faster.
lua luajit
Comments
Post a Comment