New threads as performant as new scripts?

Hello, for a system I’m writing (a dancefloor) I need to have a lot of separate functions to run simultaneously without yielding each other. Example: One function for changing the color of the lights, another one for changing the color of the tiles, …
So the way I’m doing that now is by wrapping each function inside of a coroutine that runs a while true do loop. (the functions yield internally).
Would it be better performance-wise to have each function inside of its own script?
Is there any (noticeable) difference for doing one over the other?
Thanks.

I recently ran into a similar problem and I used BindableEvents between server scripts instead of creating new threads. This doesn’t really answer your question, but I wanted to let you know another alternative.

1 Like

I suggest instead of having a lot of script instances to just have 1 to handle all; This would increase performance.

I hope this answered your question.

1 Like

New scripts is significantly slower than using coroutines. Each script creates a new context, environment, and thread. This is extremely slow. BindableEvents and coroutines have very similar efficiency, with coroutines being the overall fastest. The way to actually test this is sort of complicated in my experience since its hard to effectively monitor how long a script takes to start initially (iirc require is a decent way to measure this).

The reason coroutines are faster is because there is virtually no additional cost to performance. Roblox uses a threading model where one thread will run until it yields or stops, then the next thread will run until it yields or stops, then the next thread will run until it yields or stops, etc, and when resuming a coroutine, all that happens is the place where code is executing is just moved to that thread and back after the first yield or until it stops.

That effectively means that the cost of creating a coroutine is virtually nothing, all it is is creating a structure in memory, and resuming a coroutine is only the cost of running your code up until its first yield or until it stops if it doesn’t yield.

Tl;dr, script starts are significantly slower, do not use scripts to create new threads, that will not increase performance at all.

7 Likes

That’s what I said. Only use 1 script instead of using multiple.

Ah yeah, I misunderstood what you said. My bad.

Thanks @Hexcede and @KJry_s!
This explains alot, I will use coroutines to run all the functions in one script.