Is there any value in creating local copies of common Lua functions like print()
, pairs()
or ipairs()
?
Example:
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.
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