Kotlin에서 예외를 처리하는 대표적인 두 가지 방식인
각각의 성능을 JMH 벤치마크를 통해 비교
⸻
@State(Scope.Thread)
open class TryVsEitherBenchmark {
private val random = Random(1234)
private val errorProbability = 0.1
private lateinit var errorScenarios: BooleanArray
private var index = 0
@Setup
fun setup() {
errorScenarios = BooleanArray(10_000) { random.nextDouble() < errorProbability }
}
private fun nextScenario(): Boolean = errorScenarios[index++ % errorScenarios.size]
@Benchmark
fun eitherMixed(): Either<CustomError, Int> =
if (nextScenario()) Either.Left(CustomError("fail")) else Either.Right(1 + 1)
@Benchmark
fun tryCatchMixed(): Int = try {
if (nextScenario()) throw RuntimeException("fail")
1 + 1
} catch (e: Exception) {
-1
}
@Benchmark
fun plain(): Int = 1 + 1
}
@JvmInline
value class CustomError(val message: String)
| 벤치마크 방식 | 초당 연산 횟수 (ops/s) | 기준(plain) 대비 성능 |
|---|---|---|
| plain (기준) | 3,502,444,726 ops/s | 100% |
| eitherMixed (Either) | 324,691,946 ops/s | 9.3% (약 10배 느림) |
| tryCatchMixed (try-catch) | 16,596,634 ops/s | 0.47% (약 210배 느림) |
jitwatch 로그 분석 결과 JVM Inline도 되지 않음)