lua-users home
lua-l archive

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


On Tue, 2008-08-05 at 17:50 -0400, Chris Camfield wrote:
> I understand from previous threads that using globals is more expensive  
> than locals.  What I'd like to ask is - is this based simply on the number  
> of table lookups, or is there anything beyond that?  I assume that the  
> cost of any table lookup is equal, including referencing "self".  Is that  
> right?

They actually work by totally different mechanisms. Lua locals are
lexically scoped true variables, and exist on the Lua stack[1]
internally. When you access a local, it's referred to directly[2]
without any table lookup happening at all. Lua globals aren't really
variables at all; they're simply syntactic sugar for doing table
accesses on _G. This:

  local a = fnord

...is equivalent to:

  local _G = {} -- actually defined internally
  local a = _G["fnord"]

This is why innocent statements like this:

  for i = 1, string.length(s) do
    table.insert(t, string.sub(i, 1, 1))
  end

...are so perilous; this is equivalent to:

  for i = 1, _G["string"]["length"](s) do
    _G["table"]["insert"](t, G["string"]["sub"](i, 1, 1))
  end

In other words, each iteration of the loop is doing four unnecessary
table lookups! Contrast with:

  local table_insert = table.insert
  local string_sub = string.sub
  local string_length = string.length
  for i = 1, string_length(s) do
    table_insert(t, string_sub(i, 1, 1))
  end

...which doesn't do any.



[1] Gross simplification. The Lua 'stack' also exists as Lua
'registers'.

[2] Gross simplification. Locals referred to via upvalues actually have
to get fetched into a register before you can use them; but this is all
happens internally, invisible to the user, and is still vastly faster
than doing a table lookup.

-- 
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│ "Thou who might be our Father, who perhaps may be in Heaven, hallowed
│ be Thy Name, if Name Thou hast and any desire to see it hallowed..."
│ --- _Creatures of Light and Darkness_, Roger Zelazny

Attachment: signature.asc
Description: This is a digitally signed message part