Optimising Using Local Variables |
|
"Local variables are very fast as they reside in virtual machine registers, and are accessed directly by index. Global variables on the other hand, reside in a lua table and as such are accessed by a hash lookup." -- Thomas Jefferson
GameState
, needs global scope for access from C, make a secondary variable that looks like 'local GSLocal = GameState
' and use GSLocal
within the module. This technique can also be used for functions that are called repetitively, too. eg.
x = { a=1,b=2 } function foo() local y=x print( x.a ) print( y.b ) -- faster than the print above since y is a local table end
(Steve Dekorte) I just got around to playing with this and it works great. For example this code:
local i, v = next(t, nil) while i do i, v = next(t, i) end
next
a local:
local next = next local i, v = next(t, nil) while i do i, v = next(t, i) end
for i, v in t do end -- about 5x as fast as a while
Keep in mind that what Steve is measuring in his tests is loop overhead (the loop body is empty). In reality there are some statments in the body so the overhead is not so significant. -- John Belmonte