String.replaceAll is considerably slower than doing the job yourself

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

    While using regular expressions imparts some performance impact, it should not be as terrible.

    Note that using String.replaceAll() will compile the regular expression each time you call it.

    You can avoid that by explicitly using a Pattern object:

    Pattern p = Pattern.compile("[,. ]+");
    
    // repeat only the following part:
    String output = p.matcher(input).replaceAll("");
    

    Note also that using + instead of * avoids replacing empty strings and therefore might also speed up the process.

提交回复
热议问题