I often write an additional check for the completed action, but now I’m wondering if it’s even needed in Roblox Studio or, on the contrary, it’s just a waste of performance?
Which is better to use?
A
local function Day()
game.Lighting.ClockTime = 12
end
-- Can be called multiple times
game.ReplicatedStorage.SetDay.Event:Connect(Day)
B
local function Day()
if game.Lighting.ClockTime ~= 12 then
game.Lighting.ClockTime = 12
end
end
-- Can be called multiple times
game.ReplicatedStorage.SetDay.Event:Connect(Day)
It’s very rare that the clock time will be exactly noon at any given point, so while it’s an extremely small waste of resources, it is definitely not needed.
Here’s a very simplified explanation of how both statements will run in the machine.
A:
Go to memory address where .ClockTime is.
Set value to 12.
B:
Go to memory address where .ClockTime is.
Get value at address.
Check if value is not 12.
Go to memory address where .ClockTime is.
Set value to 12.
A has fewer steps than B, so A will perform faster.
Code to prove this performance difference: (keep in mind, workspace.Gravity starts off at 196.2)
local firstStartingTime = os.clock()
for i = 1, 10000000 do
workspace.Gravity = 196.2
end
print("no check: ".. os.clock() - firstStartingTime .." seconds")
local secondStartingTime = os.clock()
for i = 1, 10000000 do
if workspace.Gravity ~= 196.2 then
workspace.Gravity = 196.2
end
end
print("if value ~= n then: ".. os.clock() - secondStartingTime .." seconds")
Output:
no check: 0.9446476000011899 seconds
if value ~= n then: 1.595664400003443 seconds