Android Gradle: javaMaxHeapSize "4g" 是什么?

Android Gradle: What is javaMaxHeapSize "4g"?

在一个android项目中,build.gradle文件,我已经通过了这一行

dexOptions{
    javaMaxHeapSize "4g"
}

我想知道 javaMaxHeapSize 的确切用途以及 4g 的含义。我可以提供哪些其他价值?

这是一个未记录的选项,用于增加 dex 操作的堆大小:https://groups.google.com/d/msg/adt-dev/P_TLBTyFWVY/4TPJ2YY6khUJ

, it is just an option to specify the maximum memory allocation pool for a Java Virtual Machine (JVM) for dex operation. And it's the same, as to provide to java the -xmx argument. Due to it's source codes from here 中所述,setter 看起来像:

if (theJavaMaxHeapSize.matches("\d+[kKmMgGtT]?")) {
    javaMaxHeapSize = theJavaMaxHeapSize
} else {
    throw new IllegalArgumentException(
            "Invalid max heap size DexOption. See `man java` for valid -Xmx arguments.")
}

所以,你可以看到,接受的值应该匹配 \d+[kKmMgGtT]? 模式,因此不是,它甚至指的是 man java 来了解,如何设置 -xmx。你可以阅读the man page here。它说,这个标志:

Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration.

在您的示例中,4g 是 4 GB,这是 dex 操作的最大堆大小。

dexOptions{
    javaMaxHeapSize "4g"
}

build.gradle 中写完后转到 gradle.properties 并启用此行:

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

它是 gradle 在创建构建(apk 文件)时可以使用的最大 Ram。这可以根据项目结构和大小进行更改,允许至少“4g”Ram 总是安全的,但是有时我们也需要提高它,就像我们想使用 minifyEnabled trueshrinkResources true 标志在 gradle 中用于发布构建