Are there known difference(s) between String.replaceAll() and Matcher.replaceAll() (On a Matcher Object created from a Regex.Pattern) in terms of performance?
Also, what are the high-level API 'ish differences between the both? (Immutability, Handling NULLs, Handling empty strings, etc.)
The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.
public String replaceAll(String regex, String replacement) The replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement.
String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex.
Matcher Class - Used to search for the pattern. PatternSyntaxException Class - Indicates syntax error in a regular expression pattern.
According to the documentation for String.replaceAll
, it has the following to say about calling the method:
An invocation of this method of the form
str.replaceAll(regex, repl)
yields exactly the same result as the expressionPattern.compile(regex).matcher(str).replaceAll(repl)
Therefore, it can be expected the performance between invoking the String.replaceAll
, and explicitly creating a Matcher
and Pattern
should be the same.
Edit
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.
Source code of String.replaceAll()
:
public String replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceAll(replacement); }
It has to compile the pattern first - if you're going to run it many times with the same pattern on short strings, performance will be much better if you reuse one compiled Pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With