由于使用 NDK 的应用程序的行为应该与使用 SDK 开发的应用程序类似,我认为合理堆使用的最佳指导来自ActivityManager.java的注释。
/**
* Return the approximate per-application memory class of the current
* device. This gives you an idea of how hard a memory limit you should
* impose on your application to let the overall system work best. The
* returned value is in megabytes; the baseline Android memory class is
* 16 (which happens to be the Java heap limit of those devices); some
* device with more memory may return 24 or even higher numbers.
*/
public int getMemoryClass() {
return staticGetMemoryClass();
}
/** @hide */
static public int staticGetMemoryClass() {
// Really brain dead right now -- just take this from the configured
// vm heap size, and assume it is in megabytes and thus ends with "m".
String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
}
为 Dalvik VM 设置堆大小的代码位于AndroidRuntime.cpp中,并提供了一个示例,说明如何使用property_get函数在本机代码中确定堆分配的粗略限制。
strcpy(heapsizeOptsBuf, "-Xmx");
property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
//LOGI("Heap size: %s", heapsizeOptsBuf);
opt.optionString = heapsizeOptsBuf;
mOptions.add(opt);
的默认值16m
可能很重要,因为我拥有的两部 Android 手机都没有dalvik.vm.heapsize
默认设置该属性。