This is probably an incredibly simple question, as well as likely a duplicate (although I did try to check beforehand), but which is less expensive when used in a loop, String.replaceAll()
or matcher.replaceAll()
?
While I was told
Pattern regexPattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcher;
String thisWord;
while (Scanner.hasNext()) {
matcher = regexPattern.matcher(Scanner.next());
thisWord = matcher.replaceAll("");
...
}
is better, because you only have to compile the regex once, I would think that the benefits of
String thisWord;
while (Scanner.hasNext()) {
thisWord = Scanner.next().replaceAll("[^a-zA-Z0-9]","");
...
}
far outweigh the matcher
method, due to not having to initialize the matcher
every time. (I understand the matcher
exists already, so you are not recreating it.)
Can someone please explain how my reasoning is false? Am I misunderstanding what Pattern.matcher()
does?