【发布时间】:2015-08-05 13:26:24
【问题描述】:
我的应用程序在一个 ArrayList 中存储了大量(大约 700,000 个)字符串。字符串是从这样的文本文件中加载的:
List<String> stringList = new ArrayList<String>(750_000);
//there's a try catch here but I omitted it for this example
Scanner fileIn = new Scanner(new FileInputStream(listPath), "UTF-8");
while (fileIn.hasNext()) {
String s = fileIn.nextLine().trim();
if (s.isEmpty()) continue;
if (s.startsWith("#")) continue; //ignore comments
stringList.add(s);
}
fileIn.close();
稍后,使用此代码将其他字符串与此列表进行比较:
String example = "Something";
if (stringList.contains(example))
doSomething();
这种比较会发生数百(数千?)次。
这一切都有效,但我想知道是否有什么我可以做的来使它变得更好。我注意到当加载 700K 字符串时,JVM 的大小从大约 100MB 增加到 600MB。字符串主要是这个大小:
Blackened Recordings
Divergent Series: Insurgent
Google
Pixels Movie Money
X Ambassadors
Power Path Pro Advanced
CYRFZQ
我可以做些什么来减少内存,还是可以预料到的?一般有什么建议吗?
【问题讨论】:
-
contains是非常慢的方法(O(n)) -
JEP 254 / java 9 会带来紧凑的字符串;您可以在那里阅读一些关于字符串内存消耗和运行时性能的想法。
-
特里可以帮助你
-
@fge 这个问题,他想减少内存使用,为什么不用
stream和filter不存储文件内容? -
@chengpohi 表演!一个 trie 将比这里的列表占用更少的内存