In therms of performance, which is better?

A doubt has been tormenting me. Is it better to test for equality or override when assigning a value to a variable? The first is a logical test. The second, a change in data. I believe it is the first, but what is the most effective method?

Examples:

-- Even if the state is equal to the current state, assign it:
Remote.SyncStateAttack.OnServerEvent(function(state)
    StateMachine.attacking = state
end)
-- Or test equality before assignment:
Remote.SyncStateAttack.OnServerEvent(function(state)
    if StateMachine.attacking == state then return end
    StateMachine.attacking = state
end)

2 Likes

I think about this, also, but I’m pretty sure, fundamentally it makes sense for the first option to be faster. In computer memory, on a basic level and according to my understanding, the second option should take more instruction count to execute, but with extra instructions primarily.

When i have situations like this, I always go with the former, don’t check. Because even if it is the same, it won’t change,

For example, would you rather have an auto-lock system on your safe, that attempts to lock everytime you leave, or CHECK if it’s locked everytime you use it and leave?

Well the autolock is faster, you don’t have to take the time to check. I vote number 1.

1 Like

Copying small amounts of data is a relatively light operation. Branches in code, however, aren’t. Stick with the first option.

1 Like

From experience, reading properties and assigning a value to a property is kind of slow on Roblox. I also did not notice any optimization from roblox in the case that you overwrite a property with the value it was at already. However, you are reading the property in the if statement so that kind of defeats the purpose (in an ideal world, you would store the previous value as a variable and compare that one to the new one, and change the value of that variable alongside the property)

If it’s for a single operation, you shouldn’t bother with the first one but if you are playing with the properties of hundreds of objects, it can be a good idea to limit how often properties are being changed

1 Like

The first is the most effective. If you ever wonder about performance, just benchmark it.

There is also a post similar to this where I explained why and did some benchmarks: Is it better to use additional check or not? - #8 by Katrist

2 Likes