关于协程性能的疑惑:为何无协程代码运行更快?
为什么协程版本的程序运行耗时更长?
你的测试代码:
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import kotlinx.coroutines.launch import kotlin.system.measureNanoTime fun countWithoutCoroutine(target: Int) { for (i in 0..target) { println(i) } } suspend fun countWithCoroutine(target: Int) = coroutineScope { launch { for (i in 0..target) { println(i) } } } fun main() { val timeWithCoroutine = runBlocking { measureNanoTime { countWithCoroutine(50) } } println("Time Taken with coroutines : $timeWithCoroutine") val timeWithoutCoroutine = measureNanoTime { countWithoutCoroutine(50) } println("Time take without coroutines: $timeWithoutCoroutine") }
原因分析:
- 协程存在初始化与调度开销:协程版本需要创建
coroutineScope、启动launch协程,这些操作都会产生额外的CPU开销,而普通版本只是直接执行循环打印,没有这些额外步骤。 - 未利用协程的并行优势:你只在协程作用域里启动了一个协程,本质上和普通同步执行的逻辑完全一致,反而多了协程调度的成本。协程的优势要在多任务并行或者IO密集型场景下才能体现——比如同时启动多个协程处理不同任务,或者在等待IO的时候让出线程资源,而单协程做同步任务只会徒增开销。
- 冷启动与类加载开销:第一次运行协程相关代码时,JVM需要加载Kotlin协程库的相关类,这部分冷启动耗时被算进了协程版本的测量时间里,而普通函数没有这部分额外加载成本。
内容的提问来源于stack exchange,提问作者james
相关产品推荐
相关产品推荐

