我正在阅读《Lua程序设计(第2版)》,看到下面这段话:
在编程时尽可能使用本地变量是良好的编程风格。本地变量有助于避免将不必要的名称杂乱无章地添加到全局环境中。此外,访问本地变量比访问全局变量更快。
有人能解释一下为什么吗?这个“特性”只存在于Lua中,还是其他语言也有呢?(例如C、C ++、Java)
我正在阅读《Lua程序设计(第2版)》,看到下面这段话:
在编程时尽可能使用本地变量是良好的编程风格。本地变量有助于避免将不必要的名称杂乱无章地添加到全局环境中。此外,访问本地变量比访问全局变量更快。
有人能解释一下为什么吗?这个“特性”只存在于Lua中,还是其他语言也有呢?(例如C、C ++、Java)
文件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)