kotlin-tooling-native-build-performance

작성자: kotlin

Kotlin Multiplatform 프로젝트에서 iOS를 대상으로 할 때 느린 Kotlin/Native 컴파일 및 링크를 진단하고 수정합니다. 사용자가 느린 iOS 또는…을 보고할 때 사용하세요.

npx skills add https://github.com/kotlin/kotlin-agent-skills --skill kotlin-tooling-native-build-performance

Kotlin/Native Build Performance

Turn "the iOS build is slow" into a measured diagnosis and a small set of safe fixes. Two rules apply throughout:

  1. Never trade away required release behavior. A faster local loop must not change what CI publishes.
  2. Measure before and after with the same command and the same build state. An unmeasured fix is a guess.

Step 0: Classify the Slow Scenario

Establish four facts before editing anything: where (local or CI), what (debug feedback loop or release/distribution artifact), state (first build, clean, warm, or no-op), and phase (which tasks dominate the log). Then match the dominant symptom:

Symptom in the build logLikely causeRead
linkRelease* or *ReleaseXCFramework tasks in a local development loopBuilding distribution artifacts for developmentartifacts-and-targets
Kotlin/Native compiler distribution downloaded on every CI run~/.konan not preserved between runscaching-and-gradle
Long pause before the first task startsConfiguration phase, no configuration cachecaching-and-gradle
All iOS targets build when only one simulator is neededBroad task (build, assemble, assemble*XCFramework) or unused targetsartifacts-and-targets
ksp* tasks ahead of compileKotlinIos*Generated-code work on the native pathexports-and-generated-code
Small source edit recompiles and relinks everythingCompiler caches disabled, or missing incrementalitycaching-and-gradle, experimental
Machine overloaded while several link* tasks run at onceParallel native linkingcaching-and-gradle, worker-limit caveat

Step 1: Audit and Measure

  1. Run the static audit from the project root:

    scripts/audit-native-build.sh /path/to/project
    

    It is read-only and prints file:line findings (disabled caches, broad local tasks, transitiveExport, broad KSP configuration, missing CI .konan cache), each pointing at the reference file with the fix. Findings are leads, not verdicts — confirm each against project policy.

  2. Find the command the user actually waits for: a script, a CI step, or the Gradle invocation inside an Xcode build phase. Optimize that command, not a task you picked yourself.

  3. Run it twice when practical. The first build downloads Kotlin/Native components and fills caches; only the second and later runs are representative. Attribute time per task before blaming the compiler:

    kotlin.build.report.output=file   # writes build/reports/kotlin-build/
    

    Gradle's --scan or --profile work too.

  4. If you cannot run the build (no macOS host, no Xcode), analyze logs, build scans, or checked-in metrics instead — and state explicitly that the conclusion is static.

Step 2: Fix in Safe Order

Apply fixes one at a time, re-measuring as you go:

  1. Restore healthy defaults — remove cache/daemon workarounds, enable Gradle build and configuration caches, keep ~/.konan warm in CI, update Kotlin: references/caching-and-gradle.md
  2. Build only what the feedback loop needs — one specific task per loop, correct integration method, justified target matrix: references/artifacts-and-targets.md
  3. Cut export and generated-code cost — drop transitiveExport, narrow export(...), scope KSP work to the native compilations that need it: references/exports-and-generated-code.md
  4. Experimental switches last, with the user's agreement: references/experimental.md

Worked Example

A developer on an Apple Silicon Mac complains that "every shared-module change costs 12 minutes". Their loop runs ./gradlew :shared:assembleXCFramework. A build scan of the second (warm) run shows:

:shared:linkReleaseFrameworkIosArm64             348s
:shared:linkReleaseFrameworkIosX64               341s
:shared:compileKotlinIosX64                       96s
:shared:linkDebugFrameworkIosSimulatorArm64       41s
:shared:compileKotlinIosSimulatorArm64            38s
configuration phase                               64s

Reasoning chain:

  • The loop is local + debug + warm, but ~690s goes to linkRelease* — release linking is an order of magnitude slower than debug and only CI needs it. Replace the local command with :shared:linkDebugFrameworkIosSimulatorArm64 (or the Xcode embed task if Xcode drives the build). (artifacts-and-targets)
  • All iosX64 work serves Intel simulators; ask whether the team still supports them before removing the target. (artifacts-and-targets)
  • 64s of configuration on every run disappears behind org.gradle.configuration-cache=true once trialed. (caching-and-gradle)
  • Expected loop after the change: ~40s compile + ~40s link on warm builds — confirm by re-running the new command twice and comparing.
  • CI keeps assembleXCFramework untouched; note that explicitly in the report.

Verify

  • Re-run the exact baseline command; compare warm build against warm build, not warm against cold.
  • Second run with the configuration cache reports it is being reused.
  • The local development log no longer contains linkRelease*, *ReleaseXCFramework, or removed generator tasks.
  • CI still produces every required release artifact, unchanged.
  • Tests pass and the app still runs from Xcode.
  • scripts/audit-native-build.sh reports no findings you have not consciously accepted and documented.

Report Your Changes

Close with a short performance note:

  • The slow scenario (local/CI, debug/release, cold/warm) and the measured evidence — or a statement that the analysis was static.
  • Each change, and why it is safe for release behavior.
  • The before/after commands the user can run to confirm the win.
  • Remaining tradeoffs: experimental flags enabled, targets removed under a policy assumption, worker limits, or generated-code work deferred.
  • Links to the relevant official documentation below.

Official Documentation

TopicLink
Improving Kotlin/Native compilation timehttps://kotlinlang.org/docs/native-improving-compilation-time.html
Kotlin Gradle plugin compilation and cacheshttps://kotlinlang.org/docs/gradle-compilation-and-caches.html
iOS integration methodshttps://kotlinlang.org/docs/multiplatform-ios-integration-overview.html
Direct integration with Xcodehttps://kotlinlang.org/docs/multiplatform/multiplatform-direct-integration.html
Building final native binaries and XCFrameworkshttps://kotlinlang.org/docs/multiplatform/multiplatform-build-native-binaries.html
Kotlin/Native binary optionshttps://kotlinlang.org/docs/native-binary-options.html
KSP with Kotlin Multiplatformhttps://kotlinlang.org/docs/ksp-multiplatform.html

kotlin의 다른 스킬

ci-cd-containerization-advisor
kotlin
재현 가능한 빌드, 이미지 및 배포 파이프라인을 설계합니다. Kotlin 및 Spring 애플리케이션을 대상으로 하며, CI 검증, 계층형 컨테이너, 롤아웃 안전성 등을 포함합니다.
official
configuration-properties-profiles-kotlin-safe
kotlin
Design and diagnose Spring configuration, profiles, and `@ConfigurationProperties` binding for Kotlin applications. Use when property binding fails,…
official
dependency-conflict-resolver
kotlin
Diagnose and resolve Gradle and Spring classpath conflicts, version drift, and binary incompatibilities in Kotlin applications. Use when `NoSuchMethodError`,…
official
domain-decomposition-api-design-advisor
kotlin
구현을 시작하기 전에 비즈니스 범위를 경계 컨텍스트, 모듈 또는 서비스 경계, 워크플로우, API 계약으로 분해합니다. 새로운 것을 설계할 때 사용하세요.
official
error-model-validation-architect
kotlin
Kotlin과 Spring 서비스를 위한 일관된 API 검증 및 오류 처리 동작을 설계하고 구현합니다. 오류 페이로드를 정의하거나 프레임워크를 매핑할 때 사용합니다.
official
gradle-kotlin-dsl-doctor
kotlin
Generate, debug, and repair Kotlin + Spring Gradle builds with minimal, compatible changes. Use when `build.gradle.kts` or `settings.gradle.kts` is failing,…
official
integration-resilience-engineer
kotlin
탄력적인 HTTP, 메시징, 예약 통합을 Kotlin 및 Spring 서비스용으로 설계하며 명시적인 타임아웃 예산, 재시도, 멱등성, 서킷 브레이커를 포함합니다.
official
jackson-kotlin-serialization-specialist
kotlin
Kotlin과 Jackson을 사용하는 Spring 애플리케이션에서 JSON 직렬화 및 역직렬화 동작을 진단하고 설계합니다. DTO 역직렬화 실패 시, 기본값…
official