In Java, which is faster - String.contains("some text") or Regex that looks for same text?

10,925

Solution 1

They're both fast enough to be over before you know it. Better to go for the one that you can read more easily.

But from forums, blogs contains is faster, but still negligible performance difference

Solution 2

I had tried both approaches and repeated them over 100k times and String.contains() is a lot more faster than Regex.

However String.Contains() is only useful for checking the existence of an exact sub­string, whereas Regex allows you to do more wonders. So it depends.

Solution 3

You can test it yourself by creating benchmark using Caliper - Google's open-source framework

Read more about What is a microbenchmark?

Detailed Example

Share:
10,925
mal
Author by

mal

Updated on June 04, 2022

Comments

  • mal
    mal almost 2 years

    As the title says, just looking for a string to match a client finishing sending data over a socket, so I might be looking for something like {"Message" : "END"} in a JSON string for example. A the most the strings will be a few hundred chars long.