Skip to content

Kotlin/Native: Missing fillInStackTrace() causes performance issues with frequent coroutine cancellations #4587

@messyguuuuys

Description

@messyguuuuys

Description

In Kotlin/JVM, Throwable.fillInStackTrace() allows controlling stack trace collection, which is crucial for performance when exceptions are used for control flow (e.g., CancellationException in coroutines).

Kotlin/Native lacks this method, causing mandatory stack trace collection on every exception initialization, leading to performance degradation and app freezes when cancelling coroutines frequently.

Current Behavior

// Kotlin/Native
class MyCancellationException : CancellationException() {
    // ❌ No fillInStackTrace() to override
    // Stack trace is always collected
}

Expected Behavior

// Like Kotlin/JVM
class MyCancellationException : CancellationException() {
    override fun fillInStackTrace(): Throwable {
        return this // Skip stack trace collection
    }
}

Performance Impact

  • High-frequency job cancellations cause significant overhead
  • Stack trace collection on main thread → UI freezes
  • Measured X ms per cancellation in production

Reproduce

import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(10000) {
        launch {
            try {
                delay(Long.MAX_VALUE)
            } catch (e: CancellationException) {
                // Stack trace collected here unnecessarily
            }
        }.cancel()
    }
}

Environment

  • Kotlin version: 1.x.x
  • Kotlin/Native version:
  • Target: iOS/Android Native
  • Coroutines version: 1.x.x

Proposed Solutions

  1. Add fillInStackTrace() support to Kotlin/Native Throwable
  2. Add compiler flag to disable stack traces for specific exception types
  3. Make CancellationException not collect stack traces by default

References

  • Similar issue in coroutines: [link if exists]
  • JVM behavior documentation: [link]

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions