由于使用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属性.