LUA扣細節式優化
原測試者使用for i = 1, 1000000 do
測試效能
此範例中以 while true do 來表示
1. 序列化後的結構有利循環執行效率
```
local tbl = {1,2,3,4,5}
for k,v in pairs(tbl) do
print(k,v)
end
```
進一步選擇:
```
local tbl = {1,2,3,4,5}
for i=1,#tbl do
local v = tbl[i]
print(i,v)
end
```
2. 能在循環前用local就先用local(外部定義變量為佳及本地變量為佳),尤其循環中有表包括(math.,string.)等
```
while true do
local x = math.sin(i)
``` ### 進一步選擇:
```
local sin = math.sin
while true do
local x = sin(i)
```
3. 避免使用load、load和loadstring 在循環中(動態執行)
```
while true do load("x = 2")() end
```
進一步選擇:
```
local x = 1
while true do x = 2 end
```
4. 在循環中避免使用table.unpack
5. 在循環中為表新增初始化數據時,如果能預先定義好長度為佳,能定義好數值更佳(避免容量重置)
```
while true do
local a = {}
a[1] = 1; a[2] = 2; a[3] = 3
local b = {x=1,y=2,z=3} -- 預先定義數值
```
進一步選擇:
```
while true do
local a = {0, 0, 0} -- 預先定義表長
a[1] = 1; a[2] = 2; a[3] = 3
local b = {x=0.0,y=0.0,z=0.0}
b.x = 1; b.y = 2; b.z = 3
```
6. 文字拼接使用table.concat
```
local a,b,c = "hello","world","!"
while true do
local d = a..b..c
```
進一步選擇:
```
local a,b,c = "hello","world","!"
while true do
local d = table.concat({a,b,c})
```
進一步選擇:
```
local a,b,c = "hello","world","!"
local tt = {a,b,c}
local tc = table.concat --結合第2.
while true do
local d = tc(tt)
```
7. 表中變量越少越好
```
local items = {
{x = 1.0, y = 1.0},
{x = 1.5, y = 1.5},
{x = 2.0, y = 2.5},
...
}
while true do
for i=1, #items do
x,y = items[i].x,items[i].y
```
進一步選擇:
```
local items = {
{1.0,1.0},
{1.5,1.5},
{2.0,2.5},
...
}
while true do
for i=1, #items do
x,y = items[i][1],items[i][2]
```
進一步選擇:
```
local items = {
x = {1.0,1.5,2.0,...},
y = {1.0,1.5,2.5,...}
}
while true do
for i=1, #items.x do
x,y = items.x[i],items.y[i]
```
進一步選擇:
```
local items = {
{1.0,1.5,2.0,...}, -- items[1]
{1.0,1.5,2.5,...} --items[2]
}
while true do
for i=1, #items[1] do
x,y = items[1][i],items[2][i]
```
8. 使用判斷表時使用安全訪問在循環中
```
local tbls = {x = {pos1 = {1,2},pos2 = 2, pos3 = 3},
y = {pos1 = 1,pos2 = 2, pos3 = 3}
while true do
if tbls and tbls.x and tbls.x.pos1 and tbls.x.pos1[1] > 1 then --最多判斷了5次+從表中提取了6次
```
進一步選擇:
```
local tbls = {x = {pos1 = 1,pos2 = 2, pos3 = 3},
y = {pos1 = 1,pos2 = 2, pos3 = 3}
local e = {}
while true do
local c = (((tbls or e).x or e).pos1 or {})[1] --如果一直有值,無需臨時創建變量
if c and c > 1 then --最多判斷了4次,從表中提取了3次
```
或
```
local tbls = {x = {pos1 = 1,pos2 = 2, pos3 = 3},
y = {pos1 = 1,pos2 = 2, pos3 = 3}
while true do
local x = tbls.x
local pos1 = x and x.pos1 --需要臨時創建變量,即使一直有值
local c = pos1 and pos1[1] --寫法較需要邏輯能力,較容易出錯
if c and c > 1 then --最多判斷了4次,從表中提取了3次
```
9. 使用Single Method
```
function newObject(default)
local value = default
return function(action,newvalue)
if action == "get" then
return value
elseif action == "set" then
value = newvalue
end
end
end
```