Home > Software design >  Is creation of an instance of type ArraySlice<Character> via this approach an O(1) time operat
Is creation of an instance of type ArraySlice<Character> via this approach an O(1) time operat

Time:04-12

Re: Swift 5

let str = "my string"

let slice: ArraySlice<Character> = ArraySlice(str)

Is the ArraySlice created in O(1) time?

I'm curious because complexities pertaining to extended grapheme clusters exist; such as emojis & diacritics which are larger than normal ascii characters.

Documentation I've read says array slices can be created at O(1) time, but I've never seen an example shown as the one I present above.


How could an ArraySlice be created at O(1) time?

Wouldn't the string have to first be traversed entirely to know the actual size of each character?

ArraySlice conforms to RandomAccessProtocol, and RandomAccessProtocol conformity yields the .count O(1) benefit, which is why I ask.

CodePudding user response:

No, an array slice cannot be created in O(1) in this way. Specifically, array slices can only be created from an already existing array in O(1) time; the initializer you are calling on ArraySlice has to create a copy of the sequence you pass in (O(n)) and creates a slice out of the intermediate array it creates (O(1)):

@inlinable
public init<S: Sequence>(_ s: S)
  where S.Element == Element {

  self.init(_buffer: s._copyToContiguousArray()._buffer)
}

Wouldn't the string have to first be traversed entirely to know the actual size of each character?

This is exactly correct.

  • Related