Lua Performance
Overview
This page is copied from the CA wiki. The widget used in the performance tests is available from the CA SVN.
Other Considerations
It is a well known axiom in computing that
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
Lua coders should keep that in mind, and especially when visiting this page. Readability and maintainability are in most cases just as important, and optimizing code for every last ounce of performance can severely impact those qualities. On the other hand, some of the optimizations suggested have little bearing on readability and should generally always be applied, e.g. localization of API functions, or actually make for neater code e.g. the use of or rather than a nil-check. Generally speaking, optimize only once you are sure that there is or will be a performance bottleneck.
Performance Tests
TEST 1: Localize
Code:
local min = math.min
Results:
- Non-local: 0.719 (158%)
- Localized: 0.453 (100%)
Conclusion:
- Yes, we should localize all standard lua and Spring API functions.
TEST 2: Localized Class-Methods (with only 3 accesses!)
Code 1:
for i=1,1000000 do
local x = class.test()
local y = class.test()
local z = class.test()
end
Code 2:
for i=1,1000000 do
local test = class.test
local x = test()
local y = test()
local z = test()
end
Results:
- Normal way: 1.203 (102%)
- Localized: 1.172 (100%)
Conclusion:
- No, it isn't faster to localize a class method IN the function call.
TEST 3: Unpack A Table
Code 1:
for i=1,1000000 do
local x = min( a[1],a[2],a[3],a[4] )
end
Code 2:
local unpack = unpack
for i=1,1000000 do
local x = min( unpack(a) )
end
Code 3:
local function unpack4(a)
return a[1],a[2],a[3],a[4]
end
for i=1,1000000 do
local x = min( unpack4(a) )
end
Results:
- with [ ]: 0.485 (100%)
- unpack(): 1.093 (225%)
- custom unpack4: 0.641 (131%)
Conclusion:
- Don't use
unpack()in time critical code!
TEST 4: Determine Maximum And Set It ('>' vs. max)
Code1:
local max = math.max
for i=1,1000000 do
x = max(random(cnt),x)
end
Code2:
for i=1,1000000 do
local r = random(cnt)
if (r>x) then x = r end
end
Results:
- math.max: 0.437 (156%)
- 'if > then': 0.282 (100%)
Conclusion:
- Don't use math.[max|min]() in time critical code!