Is it more efficient to do an if-statement like this?

So what this code does is change the lighting depending on the time. The sunset/sunrise is kind of a transition.
The first time I wrote this, I didn’t have the timeCheck() function that’s currently in the code now.
It’s more readable and looks a helluva lot better than using the if-statement itself to check the time, but I’m wondering if it’s going to perform any different than before (it runs every 0.5 seconds in a Heartbeat timer). If doing this is more efficient and a scripting improvement in general, should I do this more often to simplify if-statements in the future?

The code:

		--timeCheck() checks if game.Lighting.ClockTime is within the range of numbers specified
		local sunsetCheck = timeCheck(6,7) or timeCheck(16.5,17.5)
		if sunsetCheck and not sunset then
			print("sunset / sunrise")
			
			--this function creates a tween and plays it
			tweenCreate_Play(game.Lighting, sunsetTween, {OutdoorAmbient = conditionTables.lightingValues.sunSetRise})
			sunset = true
		elseif not sunsetCheck and sunset then
			print("day / night")
			
			local dayNightCheck = timeCheck(7,16.5)
			local tweenGoal
			
			if dayNightCheck then
				tweenGoal = conditionTables.lightingValues.afternoon
			else
				tweenGoal = conditionTables.lightingValues.evening
			end
				
			tweenCreate_Play(game.Lighting, sunsetTween, {OutdoorAmbient = tweenGoal})
			sunset = false
		end

Also, any additional advice would help. I’m not exactly the greatest scripter haha, thanks!

2 Likes

If your code is running every 0.5 seconds and only checks Lighting.ClockTime once, I don’t think you need to be worried about performance. However, for any performance-critical code, there are a few pointers I can give you.

Keep in mind that these tips are mostly written based on my experience with stock Lua, and that things on Roblox may behave a bit different with the new Luau changes.

  • Calling a function is a relatively expensive operation. If you’re dependent on running the code as fast as possible, avoid function calls as much as possible.
  • Accessing global variables is ~30% slower than accessing local variables
  • Calling functions from within a table (i.e. string.sub()) repeatedly is slower than assigning a local variable to string.sub and calling the local variable instead
  • Crossing the Lua/C boundary is expensive. Sometimes, writing equivalent functions in pure Lua is actually faster.
  • print, warn and any other functions that put stuff out to your console are a lot slower than you might expect.

However, a general rule of optimizing is “don’t optimize unless you have to”. Sure, don’t write code that just sloppily wastes CPU time, but it’s generally a good idea to put readability first and design a good algorithm before applying any micro-optimizations.

Hopefully this helps! ^^

6 Likes