大量的协程虽然是轻量级的,但在要求苛刻的应用程序中仍然可能是一个问题
我想通过量化它们的实际成本来消除“太多协程”成为问题的神话。
首先,我们应该将 coroutine 本身与它所附加的 coroutine context 分开。这就是你如何以最小的开销创建一个协程:
GlobalScope.launch(Dispatchers.Unconfined) {
suspendCoroutine<Unit> {
continuations.add(it)
}
}
这个表达式的值是一个Job 持有一个挂起的协程。为了保留延续,我们将其添加到更大范围的列表中。
我对这段代码进行了基准测试,得出的结论是它分配了 140 字节 并需要 100 纳秒 才能完成。这就是协程的轻量级。
为了重现性,这是我使用的代码:
fun measureMemoryOfLaunch() {
val continuations = ContinuationList()
val jobs = (1..10_000).mapTo(JobList()) {
GlobalScope.launch(Dispatchers.Unconfined) {
suspendCoroutine<Unit> {
continuations.add(it)
}
}
}
(1..500).forEach {
Thread.sleep(1000)
println(it)
}
println(jobs.onEach { it.cancel() }.filter { it.isActive})
}
class JobList : ArrayList<Job>()
class ContinuationList : ArrayList<Continuation<Unit>>()
这段代码启动了一堆协程,然后进入休眠状态,因此您有时间使用 VisualVM 等监控工具分析堆。我创建了专门的类JobList 和ContinuationList,因为这样可以更轻松地分析堆转储。
为了获得更完整的故事,我使用下面的代码还测量了withContext() 和async-await 的成本:
import kotlinx.coroutines.*
import java.util.concurrent.Executors
import kotlin.coroutines.suspendCoroutine
import kotlin.system.measureTimeMillis
const val JOBS_PER_BATCH = 100_000
var blackHoleCount = 0
val threadPool = Executors.newSingleThreadExecutor()!!
val ThreadPool = threadPool.asCoroutineDispatcher()
fun main(args: Array<String>) {
try {
measure("just launch", justLaunch)
measure("launch and withContext", launchAndWithContext)
measure("launch and async", launchAndAsync)
println("Black hole value: $blackHoleCount")
} finally {
threadPool.shutdown()
}
}
fun measure(name: String, block: (Int) -> Job) {
print("Measuring $name, warmup ")
(1..1_000_000).forEach { block(it).cancel() }
println("done.")
System.gc()
System.gc()
val tookOnAverage = (1..20).map { _ ->
System.gc()
System.gc()
var jobs: List<Job> = emptyList()
measureTimeMillis {
jobs = (1..JOBS_PER_BATCH).map(block)
}.also { _ ->
blackHoleCount += jobs.onEach { it.cancel() }.count()
}
}.average()
println("$name took ${tookOnAverage * 1_000_000 / JOBS_PER_BATCH} nanoseconds")
}
fun measureMemory(name:String, block: (Int) -> Job) {
println(name)
val jobs = (1..JOBS_PER_BATCH).map(block)
(1..500).forEach {
Thread.sleep(1000)
println(it)
}
println(jobs.onEach { it.cancel() }.filter { it.isActive})
}
val justLaunch: (i: Int) -> Job = {
GlobalScope.launch(Dispatchers.Unconfined) {
suspendCoroutine<Unit> {}
}
}
val launchAndWithContext: (i: Int) -> Job = {
GlobalScope.launch(Dispatchers.Unconfined) {
withContext(ThreadPool) {
suspendCoroutine<Unit> {}
}
}
}
val launchAndAsync: (i: Int) -> Job = {
GlobalScope.launch(Dispatchers.Unconfined) {
async(ThreadPool) {
suspendCoroutine<Unit> {}
}.await()
}
}
这是我从上述代码中得到的典型输出:
Just launch: 140 nanoseconds
launch and withContext : 520 nanoseconds
launch and async-await: 1100 nanoseconds
是的,async-await 大约是 withContext 的两倍,但它仍然只是一微秒。您必须在一个紧密的循环中启动它们,除此之外几乎什么都不做,这会成为您应用中的“问题”。
使用measureMemory(),我发现每次调用的内存成本如下:
Just launch: 88 bytes
withContext(): 512 bytes
async-await: 652 bytes
async-await 的开销正好比withContext 高 140 字节,这是我们得到的一个协程的内存权重。这只是设置CommonPool 上下文的全部成本的一小部分。
如果性能/内存影响是在 withContext 和 async-await 之间做出决定的唯一标准,那么结论必须是在 99% 的实际用例中它们之间没有相关差异。
真正的原因是withContext()更简单直接的API,尤其是在异常处理方面:
-
async { ... } 中未处理的异常会导致其父作业被取消。无论您如何处理来自匹配的await() 的异常,都会发生这种情况。如果您还没有为此准备好coroutineScope,它可能会导致您的整个应用程序崩溃。
-
withContext { ... } 中未处理的异常只会被 withContext 调用抛出,您可以像处理任何其他异常一样处理它。
withContext 也恰好经过优化,利用了您暂停父协程并等待子协程这一事实,但这只是一个额外的好处。
async-await 应该保留给那些你真正需要并发的情况,这样你就可以在后台启动几个协程,然后才等待它们。简而言之:
-
async-await-async-await — 不要那样做,使用 withContext-withContext
-
async-async-await-await — 这就是使用它的方式。