当前位置 : 主页 > 网络编程 > lua >

为什么局部变量访问速度比lua中的全局变量快?

来源:互联网 收集:自由互联 发布时间:2021-06-23
所以我正在读Lua第二版编程,我在这里遇到这个段落: It is good programming style to use local variables whenever possible. Local variables help you avoid cluttering the global environment with unnecessary names. Moreover,
所以我正在读Lua第二版编程,我在这里遇到这个段落:

It is good programming style to use local variables whenever
possible. Local variables help you avoid cluttering the global
environment with unnecessary names. Moreover, the access to local
variables is faster than to global ones
.

有人可以解释为什么会这样吗?这个“功能”只是在Lua中,还是在其他语言中呢? (例如C,C,Java)

运行时间的差异是由于哈希表查找和数组查找之间的区别.解释器可能能够将局部变量放在CPU寄存器中,但是即使没有这样的聪明,局部变量的访问速度更快.

Lua中的全局变量存储在表中.通常,任何人都可以修改这些表,因此解释器必须在每次访问时重新查找值.另一方面,局部变量只有在超出范围时才消失.因此,它们可以在数组中具有固定位置.

下面的基准程序在循环中调用一个虚拟函数.基准测试显示运行时间如何升高程序跳过的更多表.

其他动态语言应具有类似的特征;看到Python的基准测试在最后.

一些相关链接:

> Optimising Using Local Variables(Lua)
> Local Variables(Python性能提示)
> Optimizing Global Variable/Attribute Access.(撤回)关于查找全局对本地对象的Python提案.

文件demo.lua:

local M = {}
_G.demo = M
function M.op(x) return x end
return M

文件main.lua:

local M = require "demo"

op = demo.op

local outer_op = demo.op

function iter_op(n)
    local inner_op = demo.op
    for i = 1, n do
        -- Example running times for n = 100,000,000 (Lua 5.2.0):

        -- Lookup a table (demo or _G), then lookup 'op'
        -- within that table:
        --
        -- demo.op(i)      --> 0:40
        -- _G.op(i)        --> 0:39

        -- Lookup 'op' within a known local table (M or the table of
        -- globals):
        --
        -- M.op(i)         --> 0:30
        -- op(i)           --> 0:30

        -- Dereference a local variable declared inside or outside
        -- of this iter_op() function:
        --
        -- inner_op(i)     --> 0:23
        -- outer_op(i)     --> 0:22
    end
end

iter_op(100000000)

文件main.py:

import demo # Contains 'def op(x): return x'.

global_op = demo.op

def iter_op(n):
    local_op = demo.op
    for i in xrange(n):
        # Example running times for n = 50,000,000 (Python 2.6.5):
        # demo.op(i)     # 0:50
        # global_op(i)   # 0:41
        local_op(i)      # 0:36

iter_op(50000000)
网友评论