Should I be using task.spawn() or coroutines?

My question is, should I be using coroutines to create separate threads or task.spawn? Which one is safer to use in case of memory leaks and better for performance?

5 Likes

It depends on the use case.

coroutines have much more functionality than task.spawn and have more use cases. for most people, task.spawn does the job best for general purposes

2 Likes

Coroutine

The coroutine library provides more functionality such as thread state at the cost of convenience. Threads ran via coroutine.wrap or coroutine.resume do not get tagged in the debug traceback, meaning errors that occur in the thread’s function get obscured. You also have to handle the execution of threads manually, and cannot utilize Roblox’s TaskScheduler without using the task library

Task

The task library provides convenience at the expense of less functionality to work with (ex: task.cancel does not return the thread’s state like coroutine.close). It allows you to execute threads in conjunction to the rest of the engine’s task scheduler, allowing you to reason more with the flow of things.

The task library has 3 “spawner” functions: task.spawn, task.delay and task.defer. Here’s a basic summary of how they differ:

Function Description
task.spawn Spawns the thread immediately. It can also resume “dead” threads unlike coroutine.resume.
task.delay Spawns the thread after the given duration in seconds, or immediately if nil is given.
task.defer Spawns the thread during the next resumption cycle as opposed to immediately. What this means is certain engine mechanics like parent-locking will finish before it is executed.

Generally, you will use the task library more often, but threads can be handled with both libraries interchangeably.

16 Likes

Thank you, this explained the functionality differences perfectly.
However, are there any differences in the 2 with performance?

I don’t think there is necessarily any performance differences between the two although task.spawn runs through the scheduler and coroutines run alongside a thread.

2 Likes

I would also like to point out that parallel lua (a very good structure to learn) is primarily ran with the task library. It also is easier, in my opinion, to halt tasks with libraries such as Maid and Janitor.

1 Like

With task.defer there is.

Basically, using task.spawn and coroutine.create or coroutine.wrap will create/resume the thread immediately (within the same frame). This can cause small performance issues for obvious reasons.
However, task.defer will create/resume the thread on the next “resumption cycle”, which is still almost immediate, but won’t cause those small performance issues.

5 Likes

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