最近一直在做openresty相關開發,使用lua優化,優化了幾次,發現最大的優化是table的優化。
table優化的大原則是盡量少創建表,表創建多了畢竟耗性能。這里的創建,指新創建和擴表引起的創建。在往table插入數據的過程中,如果table不夠用,會擴大兩倍,所以,一個1030項數據,會經過十次擴表,非常消耗性能。
方法一,代碼層面重用表
原始代碼:
for i, 100 do
local a = {}
a.num = i
a.result = "test"
ngx.say(table.concat(a))
end
里面有多次創建表,但其實可以補創建那么多次,改為
local a = {}
for i, 100 do
a.num = i
a.result = "test"
ngx.say(table.concat(a))
end
方法二,使用table.new
table.new()是luajit新加的功能,可以在創建table的時候,指定table的大小,避免擴表操作
local new_tab = require "table.new"
local t = new_tab(100, 0)
for i = 1, 100 do
t[i] = i
end
方法三,使用table 池
table.new對應的有一個table.clear函數,用於清空表,所以可以封裝一個table池,循環使用這些table,減少table創建
local tablepool = require "tablepool"
local tablepool_fetch = tablepool.fetch
local tablepool_release = tablepool.release
local pool_name = "some_tag"
local function do_sth()
local t = tablepool_fetch(pool_name, 10, 0)
-- -- using t for some purposes
tablepool_release(pool_name, t)
end