Which would be more efficient?

Currently, I am creating a basic day/night system script which will handle enemy spawning in my survival based game. I have come up with three different methods of handling this problem, and would like to choose the most memory efficient way.

1: While Loop

No need to explain this

2: Recursion

Recursion is the act of a function calling itself. I could do this in replacement of a while loop

3: Runservice

Using the first parameter deltatime I could continuously subtract/add this amount to the time

Which method would be the most cost-efficient in terms of lag? Are there any other methods? Am I overthinking this? Yea probably lmao

1 Like

I’m not an expert on the internals of the Luau compiler but from a coding standpoint I’d have thought using a while loop would make the most sense unless you really need to update it many times a second (in the case of using RunService). Using a recursive function just seems a little strange from a logic point of view.

1 Like

I might be wrong but I’ve heard from other people that using a while loop could cause memory leakage and have downsides over a long period of time. Rounds in my games are planned to be 20-45 minutes long, so I wouldn’t want anything like that happening.

A while loop in of itself cannot cause you issues. Most games use a while loop for something, so we’d be in serious trouble if that was the case. Something like you’re describing is really down to what you’re doing in the loop, such as creating events and forgetting to disconnect them.

There’s a fourth option, which (in my opinion) is the best performance-wise: it’s using TweenService. You can create a function that tweens the lighting ClockTime, and then use a listener for when the tween finishes to loop the tween.

Example: lightingTween.Completed:Connect(tweenFunction)

1 Like