Reputation: 11621
One particular IntelliJ IDEA inspection gets triggered when I have code like:
string1 = string2.replace(string3, string4);
The inspection says:
'replace()' could be replaced by compiled java.util.regex.Pattern construct.
And then offers to refactor the code for me, which results in using a constant literal Pattern.
I have this inspection turned on mainly for cases where I'm actually creating a regex dynamically. It can sometimes improve performance if I follow IntelliJ's suggestion. But in the case of String.replace()
the argument is not a regex. Is it true that following IntelliJ's suggestion in this case would not result in any performance improvement at all, and all it would do is hurt readability?
Is it possible to turn it off for String.replace()
but keep it on for String.replaceAll()
and String.replaceFirst()
? I couldn't see such an option.
Upvotes: 2
Views: 456
Reputation: 272467
The implementation1 of String.replace(String, String)
simply delegates to Pattern.compile(...).matcher(...).replaceAll(...)
. So I can't imagine a situation where using an explicit Pattern
in user code would be less performant (indeed, in many cases it's likely to end up more performant). Readability is, of course, a different question!
I'm not sure it's possible to configure the IntelliJ inspection, but you can suppress it for individual statements, methods, or classes.
1. At least in Oracle's JDK8.
Upvotes: 4