I’ve been wondering if there was any difference in doing this instead of regular if statements?
local bool = Humanoid.Health > 0 or HumanoidRootPart.Anchored and true
if bool then
--Code
end
Any performance differences?
I’ve been wondering if there was any difference in doing this instead of regular if statements?
local bool = Humanoid.Health > 0 or HumanoidRootPart.Anchored and true
if bool then
--Code
end
Any performance differences?
None that are really that significant. I normally do that as a way of type-checking inputs on functions, but if you are intending to use an if-statement it would be cleaner not to create a variable just to test a condition.
I mostly use it for convenience but I was wondering if it would actually boost some performance but thanks
Declaring a variable for the boolean expression would probably lower performance slightly more than if you just had it inside the if-then statement.
But unless this code is being repeated thousands of times in a few seconds the change is infinitesimally small. Just stick to the style that you prefer and makes the code easier to understand for you.
Oh right, I forgot about that. I’d use this if I would say set a variable based off of a conditional, thanks.
My typical use case for ternary operations is for type checking when a function must accept a specific data type or would need to revert to a default value when no argument is passed.
Example:
function module.pdf(x, mu, sig)
x = tonumber(x) or 0
mu = tonumber(mu) or 0
sig = tonumber(sig) or 1
sig = (sig > 0) and sig or 1
return math.exp(-0.5 * (((x - mu) / sig) ^ 2)) / (sig * math.sqrt(math.pi * 2))
end
With my personal preferred style, by not using if statements I can tell that those first 4 lines are meant for ensuring the input values are valid before proceeding to the actual code.
Opting for expressions over branching code CAN result in faster performance. But not always. For compiled languages it really depends how well the compiler can optimize branching code vs expression code. The CPU tries to preload instructions and it’ll make a guess on which one. If it gets it wrong, it has to unload the instructions and load in the right ones. But if the compiler knows what you are doing, it’ll optimize out the branch to speed it up which is how an expression based alternative might end up slower.
That being said this kind of stuff is usually reserved for performance intense applications and considering that Lua runs under a VM, ternary operators are mostly only good for simplifying certain operations.