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

前端之家收集整理的这篇文章主要介绍了为什么局部变量访问速度比lua中的全局变量快?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我正在读Lua第二版编程,我在这里遇到这个段落:

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

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

解决方法

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

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

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

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

一些相关链接

> Optimising Using Local Variables(Lua)@H_301_4@> @L_301_3@(Python性能提示)@H_301_4@> 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 (Python 2.6.5):
        # demo.op(i)     # 0:50
        # global_op(i)   # 0:41
        local_op(i)      # 0:36

iter_op(50000000)

猜你在找的Lua相关文章