replaceall() in java

在看到Thinking in Java中的13.6.6替换操作时,在strings/TheReplacements.java中有

1
2
s = s.replaceAll(" {2,}", " ");
s = s.replaceFirst("(?m)^ +", "");

在查阅Java API时看到java.util.regex.Matcher以及java.lang.String中都有replaceAll方法:
java.util.regex.Matcher.repalceAll(String replacement);
java.lang.String.replaceAll(String regex, String replacement);
其中有这样的解释:
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)

https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)
书中也写到:
这两个替换操作都只使用了一次replaceAll(),所以与其编译为Pattern,不如直接使用String的replaceAll()方法,开销更小。