6

Is there any value in creating local copies of common Lua functions like print(), pairs() or ipairs()?

Example:

local _print = print
local _pairs = pairs
local _ipairs = ipairs

for i, v in _ipairs(someTable) do
    _print(v)
end

I've seen some Lua written using this and am wondering if there are any benefits (performance or otherwise) to doing this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Jesder
  • 63
  • 5
  • Does this answer your question? [Why make global Lua functions local?](https://stackoverflow.com/questions/9198677/why-make-global-lua-functions-local) – user202729 Jun 27 '22 at 06:27

2 Answers2

6

The main motivation is probably performance because access to global variables requires a hash table lookup while access to local variables does not. However, you should measure the difference in your program. Don't overdo it.

Note that you don't need to use different names: you can write local print=print etc so that the rest of your program does not really need to know whether these variables are local or global.

Finally, there is a semantic difference when you save the value of a global variable into a local one: you are doing early binding; if your program calls an outside module that uses the same function, it will use the current value, not the frozen one you have. In other words, later redefinitions of say print do not affect you.

For a longer discussion of performance, read Chapter 2 of Lua Programmming Gems.

Another motivation for defining local copies of common functions is to redefine them and still retain the original functions.

lhf
  • 70,581
  • 9
  • 108
  • 149
2

This is an example in Lua Programing Gems:

Access to external locals (that is, variables that are local to an enclosing function) is not as fast as access to local variables, but it is still faster than access to globals. Consider the next fragment:

function foo (x)
  for i = 1, 1000000 do
    x = x + math.sin(i)
  end
  return x
end
print(foo(10))

We can optimize it by declaring sin once, outside function foo:

local sin = math.sin
function foo (x)
  for i = 1, 1000000 do
    x = x + sin(i)
  end
  return x
end
print(foo(10))

This second code runs 30% faster than the original one

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    Try making a local copy of `math` outside the loop in the original code and see the difference. – lhf Aug 07 '13 at 03:07