Throughout my scripts, I have been replacing if else statements that are about 4 to 6 else if statements long with tables thinking it would help for optimisation.
I’m wondering if replacing if else statements with tables is better for optimisation. I find this necessary because I need to run checks on render stepped heart beats for about 4-6 if else statements
I tried running these two functions
local v = 5
local loop = {
function()
end,
function()
end,
function()
end,
function()
end,
function()
print(tick())
end
}
print(tick()) loop[v]()
I get a difference of about 0.0001 to 0.0003
local v = 5
print(tick())
if v == 1 then
elseif v == 2 then
elseif v == 3 then
elseif v == 4 then
elseif v == 5 then
print(tick())
end
I also get around a difference of about 0.0001 to 0.0003
Would this difference be insignificant even if I was running these statements every heartbeat.
yeah indexing a table is better then a bunch of if-statements in my opinion. (atleast when you want smaller code) but i’m unaware of the exact comparisons in speed/resource usage.
yeah, if your running these sorts of checks in a fast loop, then i don’t think you’ll see much a performance difference tbh, but i imagine this decision is really based on how much you want to optimize memory usage.
for example, some BIG games would probably avoid doing this sort of action on the client (in order to preserve memory for other stuff.)
that being said it also depends on the types and amount of values that are in the table and how many references it would take to reach the specified value (if its deep within a table)
i think in the case of “preserving memory” it would be best to use a couple if-statements rather than predefining a constant table beforehand. (especially if that table is never disposed of afterwards)
but it really just depends on what your doing sometimes, so just try to keep yourself flexible, because you wont see much of a difference in memory either unless we’re talking about some bigger tables.
Thanks, I’m not really sure if there is a significant impact between the two in regards to speed but I’ll keep in mind the memory usage and I’ll more be flexible depending on the size of the statements.