Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replaceAll() vs. Matcher replaceAll() (Performance differences)

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.)

like image 412
SuPra Avatar asked Sep 23 '09 16:09

SuPra


People also ask

What is the difference between string replace and replaceAll?

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.

What does public string replaceAll replace?

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.

Does Java string replace replace all?

String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex.

What is the purpose of Matcher class used for regular expression?

Matcher Class - Used to search for the pattern. PatternSyntaxException Class - Indicates syntax error in a regular expression pattern.


2 Answers

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 expression

Pattern.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.

like image 126
coobird Avatar answered Sep 20 '22 20:09

coobird


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.

like image 30
Michael Borgwardt Avatar answered Sep 21 '22 20:09

Michael Borgwardt