Optimising Using Local Variables

lua-users home
wiki

Overview

Local variables are very quick, since they are accessed by index.

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 Johansson

Making global variables local

Local variables are very quick, since they are accessed by index. If possible, make global variables local (weird, eh?). Seriously, it works great and indexed access is always going to be faster than a hash lookup. If a variable, say 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

Note, this will also work with global functions (including standard library functions), eg.

(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

Is 10% faster if you make next a local:

local next = next

local i, v = next(t, nil)

while i do i, v = next(t, i) end

I also did some other tests and found that foreach() is ~20% faster than the equivalent while loop, while foreachi() was ~20% slower than a while loop.

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


See also: OptimisationTips
RecentChanges · preferences
edit · history
Last edited July 1, 2005 1:38 am GMT (diff)