String.replaceAll is considerably slower than doing the job yourself

后端 未结 4 1311
余生分开走
余生分开走 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:03

    As I have put in a comment [,. ]* matches the empty String "". So, every "space" between characters matches the pattern. It is only noted in performance because you are replacing a lot of "" by "".

    Try doing this:

    Pattern p = Pattern.compile("[,. ]*");
    System.out.println(p.matcher("Hello World").replaceAll("$$$");
    

    It returns:

    H$$$e$$$l$$$o$$$$$$W$$$o$$$r$$$l$$$d$$$!$$$

    No wonder it is slower that doing it "by hand"! You should try with [,. ]+

提交回复
热议问题