Performance Efficient Loops

Hello, this is more of a technical question of the ideal way to create a loop within a script. Most times event conditions will work but for the few edge cases I’m curious if anyone could fill me in on performance outcomes from multithreading a script through coroutines or using RunService event triggers.


Coroutine example:

local co = coroutine.create(function()
	while wait(1) do
		print("Hello!")	
	end
end)

coroutine.resume(co) --Later down the line use corountine.close(co) to end

RunService example:

local elapsedDelta = 0

local loopConnection = game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
	elapsedDelta += deltaTime
	if elapsedDelta >= 1 then
		elapsedDelta = 0
		print("Hello!")
	end
end) --Disconnect event connections to end this loop
1 Like

Loops and connecting events are not in themselves ill-performant, I’ve built entire games that are basically ran entirely on Heartbeat. Work is work and the work you’re doing might be slow, like if you’re looping over every descendant in game every frame or performing a gazillion raycasts or whatnot. When you actually face performance problems, the microprofiler is thankfully very straightforward to use to isolate your bottlenecks.

3 Likes

Actually, creating a single thread with a loop would be significantly better both in terms of readability and performance since you only are creating a thread once.

If you use Heartbeat, a completely new thread for the callback would get created every time the signal fired, so you would be making more work for the GC to clean + more boilerplate.

1 Like

Awesome, thanks for this feedback. I don’t know much on the task scheduler so this is helpful information. I never knew Heartbeat created multiple threads.

1 Like

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