使用Lua 局部变量来优化性能,同时比较局部变量和全局变量

本文探讨了在Lua中使用局部变量优化性能的原因,指出局部变量比全局变量更快,因为它们存储在注册表上,而全局变量则通过变量名在表中查找。尽管Lua的全局变量访问相对高效,但通过预编译和注册表,局部变量的访问速度更快。此外,文章还提供了一些使用局部变量来提高性能的实践示例,并通过测试展示了局部变量优化的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在竞争激烈的游戏行业中,尤其页游,面对策划复杂和频繁的需求,使用脚本可以降低难度和成本。在使用Lua的过程中,会经常访问全局变量来作为配置文件。

在访问全局变量时,可以通过局部变量引用全局变量来优化。当然,这样的优化毫无意义。

Locals Vs Globals  from  http://lua-users.org/wiki/LocalsVsGlobals




Comparison between local and global variables:


Implementation: Locals index an array of registers on the stack, with hard-coded integer index (at least in the standard implementation -- LuaImplementations).
Globals index from a table (or userdata), typically with variable name string, stored as constant or variable, as the key.
实现:在Lua标准实现中,使用hard-code 整数索引在 registers on the stack 上索引局部变量。
在table或者userdata中,通过string常量或者string变量作为键来索引全局变量。
Performance: The above point implies that locals can be a bit faster
Still, table indexing is a fairly efficient operation in Lua (e.g. strings are interned with precomputed hash), so this point can often be ignored unless profiling indicates optimization is needed.
性能:通过实现不同,局部变量稍微比全局变量速度快。但是,在lua table中通过string来索引也是相当快。因为字符串在lua中被内化,事先计算过hash值。
所以,除非在剖析优化性能之外,性能问题可以被忽略。
Syntax: If an environment table is set, globals can be accessed in Lua code with or without explicitly naming the environment table they come from: foo, _G.foo, or getfenv().foo (or in 5.2.0wor

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值