Java 使用多个短文本或一个大文本时,正则表达式的速度更快吗?

Java 使用多个短文本或一个大文本时,正则表达式的速度更快吗?,java,regex,Java,Regex,我想对文件的内容执行一些正则表达式替换(Java) 这样会更有效吗 读取文件的一行;regex替换它,将它添加到字符串文件,然后读取下一行;等等 或 将整个文件读入字符串文件;然后用正则表达式替换那个大字符串 这是经过调查的,还是有人知道这件事 我猜#2的性能会更好,但会占用更多内存,但我想确定一下。第二种方法会更快。但相信我的话,相信我的密码 File f = new File("somefile.txt"); // Get the file List<String> lines_

我想对文件的内容执行一些正则表达式替换(Java)

这样会更有效吗

  • 读取文件的一行;regex替换它,将它添加到
    字符串文件
    ,然后读取下一行;等等
  • 将整个文件读入
    字符串文件
    ;然后用正则表达式替换那个大字符串
  • 这是经过调查的,还是有人知道这件事


    我猜#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));
    
    请注意,我使用了一个列表来复制您的第一个场景。我想不管怎样,你必须把它作为一个列表来处理


    请注意,第二种方法在一个非常大的文件上要快100倍。因为圣经是免费的,所以我在文本中使用了它。它有4.5MB的简单文本

    第二个选项可能更快,因为将每一行附加到某个聚合字符串实际上每次都会创建一个新字符串。为什么不分析这两个方案,看看哪一个更快?这听起来更像是一个代码审查类型的问题……在某些情况下,您可以得到不同的结果。例如,如果你使用贪婪的量词,这正是我想要的!干得好&谢谢你的努力。
    Iterating and replacing over list: 156046464
    Replacing the entire string: 1473488