Is it better to use additional check or not?

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)

Is there any point in this check or not?

2 Likes

You don’t really have to check if you don’t want to, you call the function whenever and wherever you want to. :slight_smile: It is however completely up to you!

2 Likes

No. There’s no negligible performance waste but it’s just a waste of your time to write it down.

2 Likes

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.

2 Likes

Even if the time is exactly noon and your code still sets it to noon, it will run (very so slightly) faster vs a check.

2 Likes

Explain why?

A) The engine itself checks this
B) This is such a minor waste of perfomace that you shouldn’t even bother with it

2 Likes

Thanks for the answers! I’ll take this into account!

1 Like

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
3 Likes

If your problem is solved, please set a reply (yours, mine, or anyone else’s) as the solution.

1 Like

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