我有两个文件,一个包含单词长度为 3 到 6 的字典和一个包含单词 7 的字典。单词存储在用换行符分隔的文本文件中。此方法加载文件并将其插入到我存储在应用程序类中的数组列表中。
文件大小为 386 KB 和 380 KB,每个包含少于 200k 字。
private void loadDataIntoDictionary(String filename) throws Exception {
Log.d(TAG, "loading file: " + filename);
AssetFileDescriptor descriptor = getAssets().openFd(filename);
FileReader fileReader = new FileReader(descriptor.getFileDescriptor());
BufferedReader bufferedReader = new BufferedReader(fileReader);
String word = null;
int i = 0;
MyApp appState = ((MyApp)getApplicationContext());
while ((word = bufferedReader.readLine()) != null) {
appState.addToDictionary(word);
word = null;
i++;
}
Log.d(TAG, "added " + i + " words to the dictionary");
bufferedReader.close();
}
该程序在运行 2.3.3 且具有 64MB sd 卡的模拟器上崩溃。使用 logcat 报告的错误。堆增长超过 24 MB。然后我看到将目标 GC 堆从25.XXX
24.000 MB 固定。
GC_FOR_MALLOC 释放 0K,释放 12%,外部 1657k/2137K,暂停 208ms。
GC_CONCURRENT 释放 XXK,释放 14%
内存不足 24 字节分配,然后是 FATAL EXCEPTION,内存耗尽。
How can I load these files without getting such a large heap?
Inside MyApp:
private ArrayList<String> dictionary = new ArrayList<String>();
public void addToDictionary(String word) {
dictionary.add(word);
}