创建Lua函数的本地副本是否有任何性能价值? [英] Is there any performance value in creating local copies of Lua functions?

查看:87
本文介绍了创建Lua函数的本地副本是否有任何性能价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建通用Lua函数(如print()pairs()ipairs())的本地副本是否有任何价值?

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

示例:

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

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

我已经看到一些Lua使用此工具编写的,并且想知道这样做是否有任何好处(性能或其他方面)?

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

推荐答案

主要动机可能是性能,因为对全局变量的访问需要对哈希表进行查找,而对局部变量的访问则不需要.但是,您应该测量程序中的差异.不要过度使用它.

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.

请注意,您不需要使用其他名称:可以编写local print=print等,这样程序的其余部分实际上就不需要知道这些变量是局部变量还是全局变量.

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.

最后,将全局变量的值保存到本地变量时,在语义上有所不同:您正在尽早绑定;如果您的程序调用使用相同功能的外部模块,它将使用 current 值,而不是冻结的值.换句话说,以后说print的重新定义不会影响您.

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.

有关性能的详细讨论,请阅读 Lua编程宝石的第2章.

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.

这篇关于创建Lua函数的本地副本是否有任何性能价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆