Skip to main content

Pre-Compile Regexes

By default, the compiles() method of Pattern will compile the regex every time it is called. This is fine for one-off invocations but can be expensive if the regex is used repeatedly.

This will be especially prevalent within an iterative loop, where the regex is compiled for each iteration.

Beware Convenience Methods

A number of convenience methods compile a regular expression when executed:

  • Pattern.matches()
  • String.matches()
  • String.split()
  • String.replace()
  • String.replaceAll()

Benchmark Results

As can be seen from the table below, compiling the regex in advance results in an over 5x speed increase, for a simple string case.

BenchmarkCapacityNo. of InsertsParameterModeCountScoreErrorUnits
pre_compiled_regexN/AN/Ahello_darkness_my_old_friend-I-have_come_to_speak_with_you_again_oldavgt200265.868 ±26.952ns/op
non_compiled_regexN/AN/Ahello_darkness_my_old_friend-I-have_come_to_speak_with_you_again_oldavgt2001466.439 ±982.558ns/op