I had a question related to speed/efficiency of If statements.
Say I have a boolean value like
local myBoolean = true
Say I decided that I wanted to run an if statement and that this booleans values will only be true or false (This is important).
My question is, what would perform faster and does it matter enough to keep in mind?
local myBoolean = true
if myBoolean then
print(“true”)
elseif not myBoolean then
print(“false”)
end
Or would this option perform better and faster?
local myBoolean = true
if myBoolean then
print(“true”)
else
print(“false”)
end
My thought process would be that the lower example would perform better since you’re not doing any logic to see what the bool is the 2nd time, you are just running it since it didn’t meet the first condition. Am I right to think this?
In my opinion it does not make a difference at all, but only use elseif when you need another check. If you only want one check and a “catch”, then just use else.
You would be correct in thinking the second example would be faster, however the difference of speed you would see from these two statements is not evenly humanly possible. It is likely mere nanoseconds of optimization and isn’t worth worrying about unless this question was out of pure curiosity.
Speed difference is negligible. Use the first one (elseifs) if you need an explicit second conditional check, otherwise use the second one if you’re going to handle one case with all other cases following the else block.
Do whatever fits your convention and is more readable to you. In the case of a boolean operator, I typically use the second since it’s more clear: it’s obvious for a boolean that you want one action to happen if the value is X, otherwise every other value follows the other action.
This is kind of not related to the question, but sometimes if statments can get messy so most languages like C++ have another type of if statments which are called switch statments, and I don’t think these as well are better in terms of speed they are just more readable. Lua doesn’t have these btw
But really other than that, don’t worry that much about if statments, because when you are dealing with memory, the numbers are always so exact and precise.
You could be someone who is really curious and tries to compile the code to see how much data the two if statments used more about this here, so yeah don’t worry about which one of these is better, and even if there was a difference, it would be so little that it has no effect to what’s going on.
Things that you should worry about concerning speed and efficiency are things like while loop and perhaps replecating things to the client which determinds how fast things load