使用區域變數進行最佳化 |
|
「區域變數非常快速,因為它們位於虛擬機器暫存器中,並且可以直接透過索引來存取。另一方面,全域變數位於 lua 資料表中,因此透過雜湊查詢來存取。」—— Thomas Jefferson
GameState
)需要 C 存取的全域範圍,請建立一個看起來像「local GSLocal = GameState
」的次要變數,並在模組中使用 GSLocal
。這種技術也可使用在重複叫用的函式上。例如x = { a=1,b=2 } function foo() local y=x print( x.a ) print( y.b ) -- faster than the print above since y is a local table end
(Steve Dekorte) 我才剛嘗試這個,效果很好。例如,這段程式碼
local i, v = next(t, nil) while i do i, v = next(t, i) end
next
設為區域變數,則速度會增加 10%local next = next local i, v = next(t, nil) while i do i, v = next(t, i) end
for i, v in t do end -- about 5x as fast as a while
請記住,Steve 在他的測試中測量的是迴圈的開銷(迴圈主體是空的)。實際情況下,主體中會有一些陳述,因此開銷並不是那麼明顯。—— John Belmonte