[英]Does the Lua compiler optimize local vars?
當前的Lua編譯器是否足夠智能以優化用於清晰的局部變量?
local top = x - y
local bottom = x + y
someCall(top, bottom)
或者手動內聯的速度更快?
someCall(x - y, x + y)
由於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
結果通過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
如您所見,第一個變體( a
函數)有兩個額外的MOVE
指令和另外兩個本地變量。
如果您對操作碼的詳細信息感興趣,可以在lopcodes.h中查看OpCode
枚舉的注釋 。 例如, OP_ADD
的操作碼格式是:
OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
所以上面的2 [3] ADD 3 0 1
從寄存器0和1(本例中的本地x
和y
中取值,將它們加在一起,並將結果存儲在寄存器3中。這是第二個操作碼功能和相應的源代碼在第3行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.