簡單幾招提速 Kotlin Kapt編譯


https://droidyue.com/blog/2019/08/18/faster-kapt/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io

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

開啟Gradle 構建緩存支持(Gradle build cache support)

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

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

1
2 3 
kapt {  useBuildCache = true } 

 

注意:

  • 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文件中增加

1
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中加入

1
kapt.incremental.apt=true 

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

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

如何查看注解處理器是否支持增量編譯

1
2 3 4 5 6 7 8 9 10 11 12 13 
./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為例,除了更新到最新版之外,還需要增加如下的配置

1
2 3 4 5 6 7 8 9 
android {  defaultConfig {  javaCompileOptions {  annotationProcessorOptions {  arguments << ["dagger.gradle.incremental": "true"]  }  }  } ] 

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

Troubleshooting

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

最后的建議

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

References

相關內容


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM