The more coroutines i have is the more lag?

Im using coroutine allot of times in my game and im scared its gonna cause lag issues to the players of the game.

And if it does cause lag, what alternative to it doesnt cause lag?

Most of the overhead comes from what they’re doing. Using them en-masse shouldn’t be any visibly less performant than, say, using multiple scripts or anything of that nature. Generally, multithreading using coroutines and multiple scripts should be comparable in performance since for the most part they’re the same thing.

1 Like

If it does cause lag try to reduce the number of threads you’re creating.

How can i reduce the number of threads i am using

Use new threads only if it is really needed, when your script is yelding because of a wait time or a loop.

Share the script and we may be able to point you in the right direction.

i just need to know if there is an alternative for it that is faster and causes ess preformance issues

The alternative would be to create new threads only when absolutely necessary.

2 Likes

you can just re-use the same coroutine.
this is the code for a fake spawn function that just re-uses a coroutine over and over again

local freeThread: thread?

local function passFunction(func: (...any) -> (...any), ...: any)
	local thread = freeThread :: thread
	freeThread = nil
	func(...)
	freeThread = thread
end

local function newFreeThread()
	freeThread = coroutine.running()

	while true do
		passFunction(coroutine.yield())
	end
end

local function spawn(func: (...any) -> (...any), ...: any)
	if not freeThread then coroutine.wrap(newFreeThread)() end
	coroutine.resume(freeThread, func, ...)
end

this devforum post explains how it works ig, it’s a tiny bit different from this code, but it does the exact same thing
Thread Reuse: How it works, why it works - Resources / Community Tutorials - Developer Forum | Roblox

apparently, stravant’s GoodSignal is where the poster for the tutorial learned the function from

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