It highly depends on what you precalc and how expensive the calculation is. Also micro benchmarks may give a very different result compared to the same lines in a much more complex usage with bigger amounts of accessed memory etc. (but it’s typically not that often the case when using interpreted Lua).
It also depends on what you precalc and if you can’t do it in another way, f.i. I added a third option which simply does the deg2rad conversion inline and that’s much faster than the table lookups.
I moved the memory allocation out of the loop as this probably was the most time consuming part (of course the same for both tests) - you created arrays of 36000 entries within the actual benchmark loops, I guess that’s not what you intended?
And last but not least, your table lookup has a very different range of valid input. That of course depends on the code - if you know for sure all your angles are within f.i. 1-3600 (i.e. 360 degrees in 0.1 steps as used in your test) everything is fine.
But if you want to replace trig functions for angles you can’t guarantee this (because they’re the result of other calculations) you’ll have to scale and floor your angles before you do the table lookup. At this point you need a function call already and you lost all your lookup gains, because I’d expect that in most cases, the primary reason for the overhead is the function call and not the actual calculation.
[lua]
local mathRad = math.rad
local getTimer = system.getTimer
local deg2rad = {}
for i = 1, 3600 do
deg2rad[i] = mathRad(i*0.1)
end
local t1, t2, t3 = {}, {}, {}
for i = 1, 3600 do
t1[i] = 0
t2[i] = 0
t3[i] = 0
end
local numIterations = 50
local startTimeT1 = getTimer()
for i = 1, numIterations do
for j = 1, 3600 do
t1[j] = mathRad(j)
end
end
local endTimeT1 = getTimer()-startTimeT1
local startTimeT2 = getTimer()
for i = 1, numIterations do
for j = 1, 3600 do
t2[j] = deg2rad[j]
end
end
local endTimeT2 = getTimer()-startTimeT2
local DEG2RAD = math.pi/1800
local startTimeT3 = getTimer()
for i = 1, numIterations do
for j = 1, 3600 do
t3[j] = j * DEG2RAD
end
end
local endTimeT3 = getTimer()-startTimeT3
print("Duration by using math.rad: "…endTimeT1)
print("Duration by checking table: "…endTimeT2)
print("Duration by code: "…endTimeT3)
[/lua]