问题
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.
回答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
回答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 substring, whereas Regex allows you to do more wonders. So it depends.
回答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
回答4:
From How to use regex in String.contains() method in Java
String.contains
String.contains
works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.Note that
String.contains
does not check for word boundary; it simply checks for substring.
Its performance is good it will take fraction of less seconds then Regex.
Regex solution
Regex is more powerful than
String.contains
, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.
So it is taking more time of execution to parse whole string.
来源:https://stackoverflow.com/questions/28208793/in-java-which-is-faster-string-containssome-text-or-regex-that-looks-for