Google I/O 中提到的提高 Android studio 的編譯速度的幾個建議

wutongke發表於2017-06-19

Google I/O 中有一個How to speed up your slow Gradle builds 的演講,提出了一些加快Android studio編譯速度的建議,整理如下:

1. 使用最新的Android gradle外掛

Google tools team一直致力於加快Android studio的編譯速度,因此最好使用最新的Android Gradle Plugin:

buildscript {
  repositories {
    google()
  }

 dependencies {
    classpath ‘com.android.tools.build.gradle:3.0.0-alpha3’
 }
}複製程式碼

2. 避免使用multidex

我們知道當方法書超過64k時,需要配置multidex,但是如果我們的工程minSdkVersion 設定為 20 或更低值,那麼構建時間會大大增加,因為構建系統必須就哪些類必須包括在主 DEX 檔案中以及哪些類可以包括在輔助 DEX 檔案中作出複雜的決策。

這種情況下可以利用 productFlavors(一個開發定製和一個釋出定製,具有不同的 minSdkVersion值)建立兩個構建變型。

android {
    defaultConfig {
        ...
        multiDexEnabled true
    }
    productFlavors {
        dev {
            // Enable pre-dexing to produce an APK that can be tested on
            // Android 5.0+ without the time-consuming DEX build processes.
            minSdkVersion 21
        }
        prod {
            // The actual minSdkVersion for the production version.
            minSdkVersion 14
        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                                                 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile 'com.android.support:multidex:1.0.1'
}複製程式碼

3. 減少打包的資原始檔

在開發模式下,可以只打包需要的資源,不必適配所有的資原始檔:

productFlavors {
  dev {
    minSdkVersion 21
    //only package english translations, and xxhdpi resources   
    resConfigs (“en”, “xxhdpi”)
  }
}複製程式碼

4. 禁用 PNG 處理

PNG優化在預設情況下是開啟的,我們可以在開發模式下禁用:

android {
  if (project.hasProperty(‘devBuild’)){
    aaptOptions.cruncherEnabled = false
  }
}複製程式碼

5. 使用Instant run

Instant Run在android studio 3.0中有了很多的改進,可以嘗試使用。

6. 不要隨便修改配置

Gradle使用非常靈活,但是如果不正確的使用反而會降低編譯速度。比如:

//this is BAD! 這種做法會導致每次編譯 manifest檔案都需要被修改,造成不必要的編譯時間增加
def buildDateTime = new Date().format(‘yyMMddHHmm’).toInteger()
android {
  defaultConfig {
    versionCode buildDateTime
 }
}複製程式碼

正確的做法是:

def buildDateTime = project.hasProperty(‘devBuild’) ? 100 : new Date().format(‘yyMMddHHmm’).toInteger()
android {
  defaultConfig {
    versionCode buildDateTime
 }
}複製程式碼

7. 避免使用動態版本依賴

一般使用固定版本依賴即可。

8. 注意記憶體使用

要注意分配給Gradle的記憶體使用:
目前配置

org.gradle.jvmargs=-Xmx1536m複製程式碼

即可,不必再配置:

dexOptions {
 javaMaxHeapSize = ‘4g’
}複製程式碼

9. 使用Gradle caching

在Gradle 3.5中,使用cache可以快取並重複利用之前builds的生成的檔案。

# Set this in gradle.properties
org.gradle.caching=true複製程式碼

相關的演講地址:www.youtube.com/watch?v=7ll…

歡迎關注公眾號wutongke,定期推送移動開發前沿技術文章:

Google I/O 中提到的提高 Android studio 的編譯速度的幾個建議
wutongke

推薦閱讀

說一說Facebook開源的Litho
使用ConstraintLayout製作漂亮的動畫

相關文章