tom
tom

Reputation: 485

String#replaceAll vs StringUtils#replace()

Is there any reason to use String.replaceAll(String,String) instead of StringUtils.replace() at all?

Assuming both libraries are available and we are not passing in a regex.

From the few previous posts on this topic I see there are multiple tests and benchmarks pointing to that String.replace is slow, but I don't recall anyone explaining whether there is a case for using String.replaceAll over StringUtils.replace

Source for benchmark: Commons Lang StringUtils.replace performance vs String.replace

Upvotes: 3

Views: 3250

Answers (1)

Lothar
Lothar

Reputation: 5449

String.replaceAll and StringUtils.replace (assuming Apache Commons here) are two completely different beasts. The former is using a Regular Expression as search term and performs a replacement with support of Regular Expressions as well, the latter is just looking for occurrences of the given text and replaces it by the replacement text.

With String.replaceAll you can e.g. do something like this:

System.out.println("John Smith".replaceAll("^(\S+)\s*(\S+)\*$", "$2, $1"));

which will output

Smith, John

You can't do that with StringUtils.replace.

Assuming both libraries are available and we are not passing in a regex.

String.replaceAll is always parsing the search-term as Regex and performs the replacement assuming it to be using regex-functions as well, so it simply doesn't make sense to use this method without actually using Regex.

If you just want to do a simple text-replacement you just use String.replace(CharSequence c1, CharSequence c2) that was added with Java 1.5

From the few previous posts on this topic I see there are multiple tests and benchmarks pointing to that String.replace

Some sources would be nice, where you've seen that statement. The link Nexevis provided covered Java 1.4 where above method didn't exist and - without doing some tests myself now - I have doubts that the performance between String.replace(CharSequence...) and StringUtils.replace differ a lot because StringUtils' implementation looks quite straight forward and will most likely not differ a lot from the implementation in the JVM. The existence of it is purely historical because of the lack of a similar method in Java Version before 1.5

Upvotes: 6

Related Questions