Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Tăng tốc Gradle Build trong Android Studio

Gradle là hệ thống build tự động của Android, nhưng có thể chậm do nhiều nguyên nhân: cấu hình không tối ưu, download dependency liên tục, thiếu bộ nhớ JVM, parallel execution tắt... Bài viết tổng hợp các cách tăng tốc độ build hiệu quả.

1. Cấu hình gradle.properties (Quan trọng nhất)

Tạo/sửa file gradle.properties ở root project:

# Bật daemon - giữ JVM chạy nền, không khởi động lại mỗi lần build
org.gradle.daemon=true

# Chạy task song song (parallel) - tận dụng đa nhân CPU
org.gradle.parallel=true

# Chỉ cấu hình project cần thiết (on-demand)
org.gradle.configureondemand=true

# Tăng heap size cho JVM daemon (2GB-4GB tùy RAM máy)
# Máy 8GB RAM: 2g-3g, Máy 16GB+: 4g
org.gradle.jvmargs=-Xmx3g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# Cache build (Gradle 4.0+)
org.gradle.caching=true

# Không tìm kiếm dependency động (SNAPSHOT, changing modules) mỗi lần
# org.gradle.offline=true  # Chỉ bật khi làm offline hoàn toàn

2. Cài đặt Android Studio (Settings/Preferences)

Gradle Settings

File → Settings → Build, Execution, Deployment → Gradle

  • Offline work: Bật khi không cần sync dependency mới (tăng tốc 엄청)
  • Gradle JVM: Chọn JDK 11/17 (không dùng embedded JDK cũ)
  • Service Directory Path: Đặt trên ổ SSD

Compiler Settings

File → Settings → Build, Execution, Deployment → Compiler

  • ✓ Build project automatically
  • ✓ Compile independent modules in parallel
  • ✓ Use in-process dexing (dex in process)
  • Command-line Options: --offline (khi offline work bật)

3. Cấu hình build.gradle (Module: app)

Minimize build variants

android {
    // Chỉ build architecture cần thiết cho debug
    defaultConfig {
        ndk {
            abiFilters 'arm64-v8a', 'armeabi-v7a' // Loại x86, x86_64 cho debug
        }
    }
    
    // Tách build type
    buildTypes {
        debug {
            minifyEnabled false
            shrinkResources false
            // Tăng tốc debug build
            debuggable true
            // Tắt PNG crunching
            crunchPngs false
        }
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    
    // Tránh xử lý resource không cần thiết
    aaptOptions {
        cruncherEnabled = false // Tắt PNG crunching cho debug
    }
}

Dependency management

dependencies {
    // Dùng implementation thay vì api (giảm recompilation)
    implementation 'androidx.appcompat:appcompat:1.6.1'
    
    // Tránh dynamic version (1.0.+), dùng fixed version
    // implementation 'com.google.android.material:material:1.9.0'
    
    // Module dependency
    implementation project(':mylibrary')
}

4. Tăng tốc với Modularization

  • Tách code thành nhiều module (feature, library, core)
  • Chỉ build module thay đổi (Gradle hỗ trợ incremental)
  • Sử dụng implementation thay vì api để giảm dependency graph

5. Hardware & Environment

  • SSD: Bắt buộc - HDD chậm gấp 5-10 lần
  • RAM: ≥ 16GB (8GB tối thiểu, dành 3-4GB cho Gradle daemon)
  • CPU: Đa nhân (8+ cores) cho parallel execution
  • Anti-virus: Loại trừ thư mục project, .gradle, .android khỏi scan real-time

6. Gradle Build Cache & Configuration Cache

# settings.gradle (Gradle 6.5+)
buildCache {
    local {
        directory = "${rootDir}/.gradle-build-cache"
    }
}

# Bật configuration cache (Gradle 7.0+ - experimental nhưng ổn định)
# org.gradle.configuration-cache=true

7. Profile Build để tìm bottleneck

# Command line
./gradlew assembleDebug --profile
./gradlew assembleDebug --scan  # Tạo report chi tiết trên gradle.com/scans

# Trong Android Studio
View → Tool Windows → Build → Toggle "Gradle" → Execute task → View "Build Analyzer"

8. Các tip khác

  • Tránh logic phức tạp trong build.gradle (tính toán, loop, I/O)
  • Dùng gradle.properties cho biến môi trường thay vì hardcode
  • Cập nhật Gradle Wrapper thường xuyên: ./gradlew wrapper --gradle-version 8.2
  • Dùng JDK 17/21 (LTS) cho hiệu suất tốt hơn JDK 8/11
  • Tắt Instant Run (đã deprecated, thay bằng Apply Changes)

Kiểm tra hiệu quả

Trước/sau tối ưu, chạy: ./gradlew clean assembleDebug --offline và so sánh thời gian. Thường thấy cải thiện 30-70% tùy dự án.