Runtime complexity of getting the length of a stri

2020-07-24 15:17发布

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?

2条回答
Animai°情兽
2楼-- · 2020-07-24 16:12

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).

查看更多
我只想做你的唯一
3楼-- · 2020-07-24 16:24

OK, I'm trying to answer my own question. Feel free to correct me if I'm wrong.

s.characters.count  // O(N)
s.endIndex // O(1)
s.utf8.count // O(N)
s.utf16.count // O(N)
s.unicodeScalars.count // O(N)

Apple's documentation on CollectionType.count says "Complexity: O(1) if Index conforms to RandomAccessIndexType; O(N) otherwise." Since none of the Index of CharacterView, UnicodeScalarView, UTF16View or UTF8View conforms to RandomAccessIndexType, accessing their counts are all O(N).

查看更多
登录 后发表回答