我想对文件内容执行一些正则表达式替换(在 Java 中)。
这样会不会更有效率
- 读取文件的一行;正则表达式替换它,将它添加到
字符串文件
,然后读取下一行;等
或
- 将整个文件读入
字符串文件
;然后用正则表达式替换那个大字符串。
是否对此进行了研究,或者有人对此有所了解吗?
我猜 #2 的性能会更高,但会使用更多内存,但我想确定一下。
最佳答案
第二种方法会更快。但请相信我的话,接受我的代码!
File f = new File("somefile.txt"); // Get the file
List<String> lines_list = Files.readAllLines(f.toPath()); // read the file
StringBuilder str = new StringBuilder(); // the file is a list, lets create a string
lines_list.forEach(str::append); // add all of the lines to the string builder
final String fileString = str.toString(); // finally create a string from it.
long startTime = System.nanoTime();
lines_list.forEach(item -> item = item.replaceAll("\\^([0-9]+)", "<sup>$1</sup>"));
long endTime = System.nanoTime();
System.out.println("Iterating and replacing over list: "+(endTime - startTime));
startTime = System.nanoTime();
fileString.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");
endTime = System.nanoTime();
System.out.println("Replacing the entire string: "+(endTime - startTime));
结果
Iterating and replacing over list: 156046464
Replacing the entire string: 1473488
请注意,我正在使用一个列表来复制您的第一个场景。我认为无论如何,您都必须将其作为列表来处理。
请注意,第二种方法在处理非常大的文件时要快 100 倍。我在文本中使用了圣经,因为它是免费的。这是 4.5 MB 的简单文本。
关于java - 许多短片或一大段文本的正则表达式更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809450/