I got bored today, so I decided to test something out. I've wondered about the efficiency of tables and cascading if statements. Just which one is better in which setting. I ran the following:
And got this out of it:
Yes, that's a loop of 30 million tries. I started off with 100,000, but if and table2 were both less than a second... not a terribly good comparison. What I've learned today: Predefine your tables whenever possible. Also, if you're just running things through for one shot, you won't get terribly much better performance with a table. It just looks neater. Granted, even with the slowest table version, that's over a quarter of a million function calls per second on my machine.
function testif( i )
if i == 1 then
return 2
elseif i == 2 then
return 3
elseif i == 3 then
return 4
elseif i == 4 then
return 5
elseif i == 5 then
return 6
elseif i == 6 then
return 7
elseif i == 7 then
return 8
elseif i == 8 then
return 9
elseif i == 9 then
return 10
elseif i == 10 then
return 11
else
return 1
end
end
function testtable1( i )
tab = { [1]=2, [2]=3, [3]=4, [4]=5, [5]=6, [6]=7, [7]=8 , [8]=9, [9]=10, [10]=11, [11]=1}
return tab[i]
end
tab2={}
for i = 1,10 do
tab2[i] = i+1
end
tab2[#tab2+1]=1
function testtable2( i )
return tab2[i]
end
function speedtest( count )
start = os.time()
test = 1
for i = 1,count do
test = testif( test )
end
print( "if:"..os.difftime( os.time(), start ) )
start = os.time()
for i = 1,count do
test = testtable1( test )
end
print( "table1:"..os.difftime( os.time(), start ) )
start = os.time()
for i = 1,count do
test = testtable2( test )
end
print( "table2:"..os.difftime( os.time(), start ) )
end
And got this out of it:
/speedtest(30000000)
if:15
table1:107
table2:11Yes, that's a loop of 30 million tries. I started off with 100,000, but if and table2 were both less than a second... not a terribly good comparison. What I've learned today: Predefine your tables whenever possible. Also, if you're just running things through for one shot, you won't get terribly much better performance with a table. It just looks neater. Granted, even with the slowest table version, that's over a quarter of a million function calls per second on my machine.