String.replaceAll is considerably slower than doing the job yourself

后端 未结 4 1318
余生分开走
余生分开走 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条回答
  •  醉酒成梦
    2020-12-03 05:13

    replace and replaceAll uses regex internally which in most cases gives a serious performance impact compared to e.g., StringUtils.replace(..).

    String.replaceAll():

    public String replaceAll(String regex, String replacement) {
            return Pattern.compile(regex).matcher(this ).replaceAll(
                 replacement);
    }
    

    String.replace() uses Pattern.compile underneath.

    public String replace(CharSequence target, CharSequence replacement) {
      return Pattern.compile(target.toString(), Pattern.LITERAL)
             .matcher(this ).replaceAll(
               Matcher.quoteReplacement(replacement.toString()));
    }
    

    Also see Replace all occurrences of substring in a string - which is more efficient in Java?

提交回复
热议问题