In Java, Strings Much Faster than Regexes, Even for Same Operations

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 short String object fully matches each element of a list of Pattern objects.
  • StringMatchBenchmark.stringMatch — Determine if a series of short String objects equals each element of a list of String objects.
  • StringSearchBenchmark.regexSearch — Determine the number of times the exact String “Yorick” appears in the text of Hamlet using Pattern.
  • StringSearchBenchmark.stringSearch — Determine the number of times the exact String “Yorick” appears in the text of Hamlet using String.

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:

  • stringSearch is 2.75x faster than regexSearch
  • stringMatch is 30x faster than regexMatch

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.