Which of the following ways is an efficient way of determining substring containment?
if (str.indexOf("/") > -1)
or
if (str.contains("/"))
Which of the following ways is an efficient way of determining substring containment?
if (str.indexOf("/") > -1)
or
if (str.contains("/"))
The methods have different use, if you need to check if the String contains something then use the contains, but if you want to know where in the String it is eventually contained, use the indexOf method.
For single character searches such as your example, indexOf is more efficient if the argument to indexOf is a char:
I thought I'd take an empirical approach to this question, instead of guessing about how the overhead of the additional method call would affect the outcome. I took the
indexOf
benchmark from this answer, and added two benchmark methods forcontains()
(one that takes a string constant and another that takes a variable). I'm using the just-released 1.8.0_71 running on Windows x64.Note that the benchmark measurements are nanoseconds per operation. So comparing contains("z") vs. indexOf("z"), the indexOf() is very slightly faster, but by less than 0.6ns. Interestingly enough, the indirect (using the variable) has a larger difference of a little over 1ns.
I've placed the code for this benchmark on GitHub: https://github.com/tedyoung/indexof-contains-benchmark
If the goal is to determine if one String contains another, then
contains()
is the clear winner. It will make other developers more efficient in understanding your intent.Take a look at the
java.lang.String
source code. Thecontains
method is implemented using a call toindexOf
, so they are essentially the same.You should use whichever method makes your code more readable. If you are checking to see if a String contains a specific substring, use
contains
. If you are looking for the substring's starting index, useindexOf
.Edit:
A couple of answers mention that
indexOf
should be preferred overcontains
due to the fact thatcontains
makes an additional method call, and is thus, less efficient. This is wrong. The overhead caused by an additional method call in this case is totally insignificant. Use whichever method makes the most sense in the context of your implementation. This will make your code more readable.Basically both are the same,
But if you want do something via the index, you can use
indexOf
.I believe
indexOf
will be more efficient, but the difference can be ignore.