String.replaceAll is considerably slower than doing the job yourself

后端 未结 4 1315
余生分开走
余生分开走 2020-12-03 04:55

I have an old piece of code that performs find and replace of tokens within a string.

It receives a map of from and to pairs, iterates over

4条回答
  •  Happy的楠姐
    2020-12-03 05:02

    When it comes to replaceAll("[,. ]*", "") it's not that big of a surprise since it relies on regular expressions. The regex engine creates an automaton which it runs over the input. Some overhead is expected.

    The second approach (replace(",", "")...) also uses regular expressions internally. Here the given pattern is however compiled using Pattern.LITERAL so the regular expression overhead should be negligable.) In this case it is probably due to the fact that Strings are immutable (however small change you do, you will create a new string) and thus not as efficient as StringBuffers which manipulate the string in-place.

提交回复
热议问题