我发现我的应用程序存在一个瓶颈,该瓶颈随着文件中数据的增长而不断增长(请参阅下面所附的 VisualVM 屏幕截图)。
下面是getFileContentsAsList
代码。如何才能提高性能?我读过几篇关于高效文件 I/O 的文章,其中一些建议使用 Scanner
作为高效读取文件的方法。我还尝试过 Apache Commons readFileToString
但运行速度并不快。
导致应用运行速度变慢的数据文件为 8 KB...对我来说似乎不太大。
如果这看起来是更好的途径,我可以转换为像 Apache Derby 这样的嵌入式数据库。最终寻找什么可以帮助应用程序运行得更快(顺便说一句,这是一个 Java 1.7 Swing 应用程序)。
这是getFileContentsAsList
的代码:
public static List<String> getFileContentsAsList(String filePath) throws IOException {
if (ReceiptPrinterStringUtils.isNullOrEmpty(filePath)) throw new IllegalArgumentException("File path must not be null or empty");
Scanner s = null;
List<String> records = new ArrayList<String>();
try {
s = new Scanner(new BufferedReader(new FileReader(filePath)));
s.useDelimiter(FileDelimiters.RECORD);
while (s.hasNext()) {
records.add(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
return records;
}
最佳答案
必要时,ArrayList 的大小会乘以 1.5。这是 O(log(N))。 (Vector 中使用了加倍。)如果我想加快速度,我肯定会在这里使用 O(1) LinkedList 和 BufferedReader.readLine() 而不是 Scanner。很难相信读取一个 8k 文件的时间是一个严重的问题。您可以在一秒钟内读取数百万行。
关于java - 通过 VisualVM 发现文件 I/O 瓶颈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658017/