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

后端 未结 2 1490
暗喜
暗喜 2021-01-12 21:08

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

Example:



        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 21:44

    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.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题