Which one of the methods
List<T>.IndexOf()
andList<T>.FindIndex()
is more efficient in terms of processing time?
The type of T
in this instance is String
.
Which one of the methods
List<T>.IndexOf()
andList<T>.FindIndex()
is more efficient in terms of processing time?
The type of T
in this instance is String
.
IndexOf
performs a for-loop, using the Equals
implementation of the objects being searched to look for a match. FindIndex
also peforms a for-loop but evaluates a Predicate
to check for a match instead.
They each boil down to a for-loop. The difference in performance, if any, will be negligible. Here are some MSDN excerpts:
List<T>.IndexOf Method (T)
:
This method performs a linear search; therefore, this method is an O(n) operation, where n is
Count
.
List<T>.FindIndex Method (Predicate<T>)
:
This method performs a linear search; therefore, this method is an O(n) operation, where n is
Count
.
That said, the two functions would be used quite differently. The former assumes you have an object from the list, and you just need to know at what index it exists at (if any) in the list.
The latter assumes you know some criteria about an object, and you want to find the first index where an object in the list matches that criteria. There could be multiple matches, but the method returns the first match.