In Swift 2, given a string s
, what's the runtime complexity of these statements:
s.characters.count
s.endIndex
s.utf8.count
s.utf16.count
s.unicodeScalars.count
Also, if I know a string contains alphabets only, what's the most efficient way of getting the n-th character?
If you don't have access to the source code for those expressions (you don't, unless you work for Apple), and the documentation doesn't mention the complexity (it doesn't, I've checked), it might be worth actually benchmarking the operations with strings of size 1, 10, 100, 1000 and so on.
The resulting data, while not definitive, would at least give you an indication of the time complexity for each.
In terms of getting the correct character at a given index of a string, that's already covered here. Whatever method Apple will have chosen for indexing a string is going to be as fast as they can make it (they're not in the business of preferring slow code over fast, all other things being equal).
OK, I'm trying to answer my own question. Feel free to correct me if I'm wrong.
Apple's documentation on
CollectionType.count
says "Complexity: O(1) ifIndex
conforms toRandomAccessIndexType
; O(N) otherwise." Since none of theIndex
ofCharacterView
,UnicodeScalarView
,UTF16View
orUTF8View
conforms toRandomAccessIndexType
, accessing their counts are all O(N).