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.
Benchmark | Capacity | No. of Inserts | Parameter | Mode | Count | Score | Error | Units |
---|---|---|---|---|---|---|---|---|
pre_compiled_regex | N/A | N/A | hello_darkness_my_old_friend-I-have_come_to_speak_with_you_again_old | avgt | 200 | 265.868 ± | 26.952 | ns/op |
non_compiled_regex | N/A | N/A | hello_darkness_my_old_friend-I-have_come_to_speak_with_you_again_old | avgt | 200 | 1466.439 ± | 982.558 | ns/op |