Are coroutines faster than threads?

If I replace

Thread(...).start()

with

GlobalScope.launch {...}

will it be faster?

Formally, there is only one way to check this for you - execute benchmarks.

However coroutinies are faster in common (!) scenario with a lot of thread switch (!!). It means, that if you await for something in loop (for example, await new portion of data), coroutines work faster in scenario with a lot of same parallel operations, because instead of context switch (which requires expensive operations, such as sys calls, etc.) JVM just reuses the current thread.

In the other case, when you have 1.000 threads on computer with 20 cores, every time the most of them sleep. And each of them requires at about 2Mb just for stack. Coroutines work without this disadvantage.

More details, for example, here.

1 Like

Coroutines are not primarily about speed of execution, but about efficient resource utilization in async programs. As @imanushin alread pointed out switching threads is much more expensive than switching coroutines. Additionally a thread has a much bigger memory footprint.

For number crunching the result would be mostly the same with possibly a slight advantage for a pure thread, because no overhead is needed for managing coroutines. @elizarov recommended in one of his talks to use pure threads in such cases (I can not remember the source, but maybe you could find it when googling the question with his name).

1 Like