簡單幾招提速 Kotlin Kapt編譯

  • 2020 年 1 月 20 日
  • 筆記

應用Kotlin之後,涉及到註解的註解處理器依賴也會由annotationProcessor替換成kapt,和最初應用Kotlin一樣,總會讓人一種感覺,一番應用Kotlin和Kapt之後,編譯耗時更長了,不過好在Kotlin和Google 在這一方面做了很多的優化和改進,本文將簡單介紹一些配置,來實現項目編譯關於kapt這方面的加速。

開啟Gradle 構建快取支援(Gradle build cache support)

默認情況下,kapt註解處理任務並沒有利用開啟gradle的構建快取,需要我們手動增加配置開啟

開啟方式:在項目的app module下的 build.gradle 文件增加如下程式碼

1 kapt {  2     useBuildCache = true  3 }

注意:

  • kapt配置和android配置同一層級。
  • 該特性支援從Kotlin 1.2.20開始。
  • 上述配置生效需Gradle為4.3及以上,且開啟build-cache。(增加—build-cache 選項或在gradle.properties文件添加org.gradle.caching=true

並行執行kapt任務

為了加快構建速度,我們可以利用Gradle worker API實現並行執行kapt任務。

開啟方式,在gradle.properties文件中增加

kapt.use.worker.api=true

注意:

  • Gradle worker API需依賴Gradle4.10.3及以上。
  • 該特性支援自Kotlin 1.2.60
  • 啟用並行執行,會引發更高的記憶體佔用

啟用kapt編譯規避

除此之外,我們可以利用Gradle compile avoidance(編譯規避)來避免執行註解處理。

註解處理被略過的場景有

  • 項目的源文件沒有改變
  • 依賴的改變是ABI(Application Binary Interface)兼容的,比如僅僅修改某個方法的方法體。

開啟方式:

  • 對於註解依賴需要使用kapt顯式聲明
  • gradle.properties文件中增加kapt.include.compile.classpath=false

注意:

  • 該特性需 Kotlin 1.3.20 及以上

增量註解處理

Kotlin 自1.3.30引入了一個實驗功能,即支援註解增量處理。

開啟需要很簡單,在gradle.properties中加入

kapt.incremental.apt=true

但是還需要有一個前提,就是開啟Gradle的增量編譯(Kotlin 1.1.1已默認開啟)。

除此之外,關鍵的因素還是需要開依賴的註解處理器是否支援增量處理。

如何查看註解處理器是否支援增量編譯

  ./gradlew aDeb -Pkapt.verbose=true | grep KAPT    [INFO] Incremental KAPT support is disabled. Processors that are not incremental:    com.bumptech.glide.annotation.compiler.GlideAnnotationProcessor,    dagger.internal.codegen.ComponentProcessor,    android.arch.lifecycle.LifecycleProcessor.  [INFO] Incremental KAPT support is disabled. Processors that are not incremental:    butterknife.compiler.ButterKnifeProcessor,    com.alibaba.android.arouter.compiler.processor.AutowiredProcessor,    com.alibaba.android.arouter.compiler.processor.InterceptorProcessor,    com.alibaba.android.arouter.compiler.processor.RouteProcessor,    dagger.internal.codegen.ComponentProcessor,    com.google.auto.service.processor.AutoServiceProcessor.

更新依賴至最新版

上面我們看到了glide,butterknife等依賴,我們都可以通過將這些依賴更新到最新版來解決

更新加手動配置

以Dagger為例,除了更新到最新版之外,還需要增加如下的配置

./gradlew aDeb -Pkapt.verbose=true | grep KAPT    [INFO] Incremental KAPT support is disabled. Processors that are not incremental:    com.bumptech.glide.annotation.compiler.GlideAnnotationProcessor,    dagger.internal.codegen.ComponentProcessor,    android.arch.lifecycle.LifecycleProcessor.  [INFO] Incremental KAPT support is disabled. Processors that are not incremental:    butterknife.compiler.ButterKnifeProcessor,    com.alibaba.android.arouter.compiler.processor.AutowiredProcessor,    com.alibaba.android.arouter.compiler.processor.InterceptorProcessor,    com.alibaba.android.arouter.compiler.processor.RouteProcessor,    dagger.internal.codegen.ComponentProcessor,    com.google.auto.service.processor.AutoServiceProcessor.

參考鏈接https://github.com/google/dagger/issues/1120

Troubleshooting

  • 如果啟用上面的方案導致問題,可以找到對應的配置,關閉該特性。

最後的建議

  • 積極保持依賴為最新(穩定)版,否則時間越長升級成本越大。

References