暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Optimising Using Local Variables

poslua 2016-09-22
283

在 SO 上有个这样的问题「Why are local variables accessed faster than global variables in lua?」排名第一的答案是这么解释的:


The difference in running time is due to the difference between hash table lookup and array lookup. An interpreter might be able to place a local variable in a CPU register, but even without such cleverness local variables are faster to access.


Global variables in Lua are stored in tables. Generally, anyone can modify these tables, and therefore the interpreter has to lookup a value anew every time it is being accessed. Local variables on the other hand disappear only when they go out of scope. Therefore they can have fixed locations in an array.


也就是说 Lua 的 vm 是基于寄存器的,而多数的动态语言的 vm 都是基于堆栈的。这当然不是主要原因,根本的区别在于 global 需要 hash 表的查找;而 local 是直接访问数组的。具体关于 Lua table 的分析可以参考「云风的 blog 」


再说句题外话,当初我学汇编的时候,寄存器还只有 ESP EIP 什么的,一共八个。依稀记得使用 ESP 定律去脱壳,那个酸爽啊。不知道现代 CPU 发展的如何了,寄存器还是八个?知道的可以告诉我下。


不过到底性能如何?还是来测试下:



看来性能确实是有些提升的。再来看看 LuaJIT:




犀利啊!性能对比 Lua 提升了将近 350 倍!!而且对于 LuaJIT 来说,global 和 local 的差别,貌似已经没有了明显差别。


幸运的是在 OR 中也是使用的 LuaJIT,不过还是建议继续使用 “局部变量化” 全局函数这个 Resty 的编码风格。

文章转载自poslua,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论