Sam*_*urn 3 lua compiler-optimization
当前的Lua编译器是否足够智能以优化用于清晰的局部变量?
local top = x - y
local bottom = x + y
someCall(top, bottom)
Run Code Online (Sandbox Code Playgroud)
或者手动内联的速度更快?
someCall(x - y, x + y)
Run Code Online (Sandbox Code Playgroud)
由于Lua经常将源代码编译成字节代码,因此它被设计为快速单通道编译器.它确实做了一些常量折叠,但除此之外没有很多优化.您通常可以通过执行luac -l -l -p file.lua并查看生成的(反汇编的)字节代码来检查编译器的功能.
在你的情况下Lua代码
function a( x, y )
local top = x - y
local bottom = x + y
someCall(top, bottom)
end
function b( x, y )
someCall(x - y, x + y)
end
Run Code Online (Sandbox Code Playgroud)
结果int运行时的以下字节代码列表luac5.3 -l -l -p file.lua(跳过一些不相关的部分):
function <file.lua:1,5> (7 instructions at 0xcd7d30)
2 params, 7 slots, 1 upvalue, 4 locals, 1 constant, 0 functions
1 [2] SUB 2 0 1
2 [3] ADD 3 0 1
3 [4] GETTABUP 4 0 -1 ; _ENV "someCall"
4 [4] MOVE 5 2
5 [4] MOVE 6 3
6 [4] CALL 4 3 1
7 [5] RETURN 0 1
constants (1) for 0xcd7d30:
1 "someCall"
locals (4) for 0xcd7d30:
0 x 1 8
1 y 1 8
2 top 2 8
3 bottom 3 8
upvalues (1) for 0xcd7d30:
0 _ENV 0 0
function <file.lua:7,9> (5 instructions at 0xcd7f10)
2 params, 5 slots, 1 upvalue, 2 locals, 1 constant, 0 functions
1 [8] GETTABUP 2 0 -1 ; _ENV "someCall"
2 [8] SUB 3 0 1
3 [8] ADD 4 0 1
4 [8] CALL 2 3 1
5 [9] RETURN 0 1
constants (1) for 0xcd7f10:
1 "someCall"
locals (2) for 0xcd7f10:
0 x 1 6
1 y 1 6
upvalues (1) for 0xcd7f10:
0 _ENV 0 0
Run Code Online (Sandbox Code Playgroud)
如您所见,第一个变体(a函数)有两个附加MOVE指令,另外两个本地变量.
如果您对操作码的详细信息感兴趣,可以OpCode在lopcodes.h中查看枚举的注释.例如,操作码格式为OP_ADD:
OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
Run Code Online (Sandbox Code Playgroud)
所以2 [3] ADD 3 0 1from from从寄存器0和1(本地x和y本例中)中取值,将它们加在一起,并将结果存储在寄存器3中.它是该函数中的第二个操作码,相应的源代码在第3行.