问题描述
非常简单的问题,但这是来自一个C / C ++人进入Java的复杂性。
Pretty simple question, but this is coming from a C/C++ person getting into the intricacies of Java.
我知道我可以启动jUnit和一些性能我自己的测试得到答案;但我只是想知道它是否在那里。
I understand I can fire up jUnit and a few performance tests of my own to get an answer; but I'm just wondering if this is out there.
String.replaceAll()和Matcher.replaceAll()之间是否存在已知的差异(在匹配器上)在性能方面从Regex.Pattern创建的对象?
Are there known difference(s) between String.replaceAll() and Matcher.replaceAll() (On a Matcher Object created from a Regex.Pattern) in terms of performance?
此外,两者之间的高级API是什么区别? (不变性,处理NULL,处理空字符串,制作咖啡等。)
Also, what are the high-level API 'ish differences between the both? (Immutability, Handling NULLs, Handling empty strings, making coffee etc.)
推荐答案
根据,它有关于调用方法的以下内容:
According to the documentation for String.replaceAll
, it has the following to say about calling the method:
Pattern.compile(regex).matcher(str).replaceAll(repl)
因此,可以预期调用 String.replaceAll之间的性能
,并明确创建和应该是相同的。
Therefore, it can be expected the performance between invoking the String.replaceAll
, and explicitly creating a Matcher
and Pattern
should be the same.
编辑
正如评论中指出的那样,性能差异不存在将是真实的从字符串
或匹配
单次调用 replaceAll
,但是,如果需要对 replaceAll
执行多次调用,可以预期保持已编译的模式
,因此不必每次都执行相对昂贵的正则表达式模式编译。
As has been pointed out in the comments, the performance difference being non-existent would be true for a single call to replaceAll
from String
or Matcher
, however, if one needs to perform multiple calls to replaceAll
, one would expect it to be beneficial to hold onto a compiled Pattern
, so the relatively expensive regular expression pattern compilation does not have to be performed every time.
这篇关于String replaceAll()与Matcher replaceAll()(性能差异)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!