"contains" method has complexity O(n) for Range<Int>

After accidently stubling upon, I figured out, that the "contains" method for Range calls obviously the standard SequenceType implementation, which must have complexity O(n).

A construct like (0..<10000).contains(700) or bigArray.indices.contains(indexToCheck) is quite popular among some develppers.

So a specialized implementation would be helpful:

extension Range where Element: Comparable {
func contains(i: Element) -> Bool {
     return i >= self.startIndex && i < self.endIndex
}
}

Thinking about this, maybe it is a good idea, to have something like an "OrderedCollectionType" - protocol in the standard library, where the elements are guaranteed to be in order. So it would be possible to introduce binary search or an ordered insert method and performance optimizations like the above mentioned "contains"-method. Results of an sort operation could conform to this protocol. Just a quick thought.

Replies

As you already know, `contains` method is defined for SequenceType and no specialized version of `contains` for Range (which can be far more efficient like your example) is not provided.


I'm not sure you already know this or not, Swift provides an O(1) `matches` operator for Ranges. Try this:

0..<10000 ~= 700

Thanks for your reply.

The ~= operator is much better performancewise.


Although a specialized implementation wouldn't hurt anybody ...

Although a specialized implementation wouldn't hurt anybody ...

I agree. Many programmers would use `contains` where it's available.