Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance value in creating local copies of Lua functions?

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?

like image 303
Jesder Avatar asked Aug 07 '13 02:08

Jesder


People also ask

What is Lua variables?

Lua - Variables. A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore.

What are formal parameters in Lua programming?

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While creating a Lua function, you give a definition of what the function has to do.

What are the parts of a method in Lua programming?

A method definition in Lua programming language consists of a method header and a method body. Here are all the parts of a method − Optional Function Scope − You can use keyword local to limit the scope of the function or ignore the scope section, which will make it a global function.

How to keep Lua performance high?

Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.


Video Answer


1 Answers

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.

like image 129
lhf Avatar answered Sep 21 '22 02:09

lhf