Based on the results of this JMH benchmark, string operations are faster than regex operations in Java, even if the two operations are logically the same, like String.equals and Pattern.matcher/Matcher.matches.
In some cases, much faster.
The Benchmark
The measurements include the following benchmarks:
StringMatchBenchmark.regexMatch— Determine if a series of shortStringobject fully matches each element of a list ofPatternobjects.StringMatchBenchmark.stringMatch— Determine if a series of shortStringobjects equals each element of a list ofStringobjects.StringSearchBenchmark.regexSearch— Determine the number of times the exactString“Yorick” appears in the text of Hamlet usingPattern.StringSearchBenchmark.stringSearch— Determine the number of times the exactString“Yorick” appears in the text of Hamlet usingString.
The Results
Benchmark Mode Cnt Score Error Units
StringMatchBenchmark.regexMatch thrpt 15 3675382.169 ± 9559.442 ops/s
StringMatchBenchmark.stringMatch thrpt 15 110346323.370 ± 12741407.378 ops/s
StringSearchBenchmark.regexSearch thrpt 15 4642.166 ± 5.847 ops/s
StringSearchBenchmark.stringSearch thrpt 15 12705.885 ± 19.777 ops/s
In other words:
stringSearchis 2.75x faster thanregexSearchstringMatchis 30x faster thanregexMatch
Conclusions
If speed matters, then prefer to use String operations over Pattern operations. Remember that speed does not always matter. If you’re trying to figure out if speed matters, then this might help.
