I’ve got a number of other tips which are focussed more on optimising for speed rather than memory usage.
- Populating large arrays
[lua]
local arr = {}
local arrCnt = 1
for a = 1, 50000, 1 do
arr[arrCnt] = {5, 1, 0, 0, “stuff”}
arrCnt = arrCnt + 1
end
[/lua]
is over 3.5 faster than:
[lua]
local arr = {}
for a = 1, 50000, 1 do
arr[#arr+1] = {5, 1, 0, 0, “stuff”}
end
[/lua]
- Populating small arrays
If you know how exactly big a table is going to be in advance, but don’t yet have the data to fill it yet.
[lua]
local arr = {true, true, true, true}
for a = 1, 4, 1 do
arr[a] = someCalculation(a)
end
[/lua]
Is quicker than:
[lua]
local arr = {}
for a = 1, 4, 1 do
arr[#arr+1] = someCalculation(a)
end
[/lua]
- Building large queries from strings
You might be building a dynamic query to interrogate an online DB or a local SQLlite DB, with a number of parameters, using the “…” concatenate command to build up the query string.
Putting all the components of the query into a table, and then creating the final query string at the end using table.concat is noticeably faster. This is vital in places where I’m doing up to 80,000 dynamic inserts or updates on an SQLlite table.
- Avoid while loops
If you need to loop until a certain criteria is fulfilled, a while loop is handy but expensive.
[lua]
for a = 1, 100000, 1 do
local b = math.random(1,1000)
if b == 50 then
break
end
end
[/lua]
is much faster than (assuming the 50 is found on the same iteration):
[lua]
local b = 0
while b ~= 50 do
b = math.random(1,1000)
end
[/lua]
- Avoid inPairs, if possible
Say I am iterating over all the attributes a footballer has, to calculate his influence on the next passage of play:
att.drb = 15
att.pas = 7
att.tac = 12
It is much more efficient to either store these as a numbered array rather than keys (which uses less memory but is less easy to debug later), or store the key names in a numbered array and iterate that way.
SLOW:
[lua]
local inf = 0
local fac = {drb = 0.4, pas = 1, tac = 0.2}
for k, v in pairs(att) do
inf = v * fac[k]
end
[/lua]
FASTER:
[lua]
local inf = 0
local fac = {drb = 0.4, pas = 1, tac = 0.2}
local nms = {“drb”, “pas”, tac"}
for a = 1, #nms, 1 do
local k = nms[a]
local v = att[k]
inf = v * fac[k]
end
[/lua]