1. 程式人生 > >Android Studio提升Gradle的構建

Android Studio提升Gradle的構建

用過Android Studio搞大型專案的同學應該知道,構建一次的時間很長,我的專案快的需要4分鐘左右,慢的時候要5-8分鐘,不能忍...

查了Android Developers官方,才知道了Android Plugin For Gradle 2.1 有一個能提升構建速度的特性。這面摘自官方:

Added support for dexing-in-process which performs dexing within the build process rather than in a separate, external VM processes. This not only makes incremental builds faster, but also speeds up full builds. The feature is enabled by default for projects that have set the Gradle daemon's maximum heap size to at least 2048 MB. You can do this by including the following in your project'sgradle.properties

 file:

org.gradle.jvmargs =-Xmx2048m

If you have defined a value for javaMaxHeapSize in your module-level build.gradle file, you need to set org.gradle.jvmargs to the value of javaMaxHeapSize + 1024 MB. For example, if you have set javaMaxHeapSize to "2048m", you need to add the following to your project's gradle.properties

 file:

org.gradle.jvmargs =-Xmx3072m

To disable dexing-in-process, add the following code to your module-level build.gradle file:

android {...
  dexOptions {
      dexInProcess false}}
於是順便查了dexOptions的其他屬性:

  Properties

Property Description

Whether to run the dx compiler as a separate process or inside the Gradle daemon JVM.

Specifies the -Xmx value when calling dx. Example value is "2048m".

Enable jumbo mode in dx (--force-jumbo).

The maximum number of concurrent processes that can be used to dex. Defaults to 4.

Whether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.

Number of threads to use when running dx. Defaults to 4.

查閱相關文件後,build.gradle做出瞭如下配置:
    dexOptions {
        javaMaxHeapSize "4g"
        incremental true
        preDexLibraries = false
        dexInProcess false
        maxProcessCount = 4
        threadCount = 4
    }
gradle.properties主要是將幾個地方的註釋開啟,分別是:
org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
上面這麼配置之後發現構建的速度沒提升多少,網上查了很多資料,感覺挺散,又或許我沒配置對,於是翻閱了一些資料之後,發現如果勾選setting一些其他配置,就可以有明顯的速度提升:

這裡,所有的配置設定就完成了,就這麼簡單,這樣設定之後,發現構建速度真的是大幅度提升,我的專案變成了1-2分鐘。 希望對需要的人有用,這裡有個注意點,由於每個人的電腦配置不同,所以下面的配置設定建議先註釋掉
//    dexOptions {
//        javaMaxHeapSize "4g"
//        incremental true
//        preDexLibraries = false
//        dexInProcess false
//        maxProcessCount = 4
//        threadCount = 4
//    }
這裡建議試試在完成其他配置設定的條件下,通過觀察註釋掉跟不要註釋這段配置來看看哪種情況構建速度快,我電腦。。。額,配置不想說了,所以我毅然註釋掉了。