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

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

问题描述

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

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 值,而不是您拥有的冻结值.换句话说,以后重新定义 say 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 Programmming Gems 的第 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天全站免登陆