Do order in conditional statements matter for optimization

Hey, so i was curious if there is difference between in what order i place statements in my condition, here is example:

if debounce and target then
  -- code to do something with target if there is no debounce
end

or

if target and debounce then
  -- same code
end

The thing i wanted to ask is, if i first check one variable and second is not true, but also one of those two variables are mostly true / false, is it good to check if this more dynamic variable such as debounce first? or it doesn’t make any difference?

I will tell you something what I know from my experience. Look at the code below.

local object = workspace.Baseplate
if object and object:FindFirstChild("NamelessObject") then
	-- Do something here
end

I used something like that multiple times and from doing something like that I know that if the first statement is nil or false, the second check will not be done. So in conclusion if you want to optimise your code, put first something what has higher chance of being false or nil.

This is how it is according to my experience and logic. If you revert the checks in the code provided by me, it might cause an error (if object is nil). However if you keep the same order of checks, no matter what the code will not produce errors.

1 Like

hmmm interesting point, thanks for sharing experience, you helped me a lot, thx

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.