I heard that if
statements can be really performance-heavy. Since Roblox is a well-designed platform, I suppose if
s are optimized. Right?
I wouldn’t worry too much. I don’t see what choice you have as there aren’t really many alternatives to an if statement?
You will need to benchmark it to get a concrete answer, luckily @Eestlane771 has done the heavy lifting here:
if
statements are pretty optimized. Only thing is that if you use them too much with elseif & else, it may make your code look messy. I would refer to that benchmark above.
Everything can be performence heavy if done the wrong way.
Few If
statements is not a big deal but sometimes there are better ways to handle them.
Say you wanna run a certain function if a variable is equal to something.
With If
statements it’d look something like this.
local var = "a"
function a(arg) return arg end
function b(arg) return arg end
--//Using if statements
if var == "a" then
a(nil)
elseif var == "b" then
b(nil)
end
But you can handle it with tables.
local var = "b"
--//Using tables
local functions = {
a = function(arg) return arg end;
b = function(arg) return arg end;
}
functions[var](nil)
In the end it really depends on what you’re doing.
the issue is not the amount of elseifs, but the amount at which they’re polled;
if you have 30 if’s that constantly run every frame, yeah that’ll be performance heavy
That won’t happen any time soon.
Just a reminder, you only need to use tables when you need to check various case (because them have jump table), conditional statements are fast, you don’t need to worry