通过这种方法创建 ArraySlice<Character> 类型的实例是 O(1) 时间操作吗?

Is creation of an instance of type ArraySlice<Character> via this approach an O(1) time operation?

回复:Swift5

let str = "my string"

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

ArraySlice是在O(1)时间创建的吗?

我很好奇,因为存在与扩展字素簇相关的复杂性;例如 emojis & diacritics 比普通的 ascii 字符大。

我读过的文档说可以在 O(1) 时间内创建数组切片,但我从未见过如上文所示的示例。


如何在 O(1) 时间内创建 ArraySlice?

是不是要先遍历整个字符串才能知道每个字符的实际大小?

ArraySlice 符合 RandomAccessProtocolRandomAccessProtocol 符合会产生 .count O(1) 的好处,这就是我问的原因。

,这种方式O(1)无法创建数组切片。具体来说,数组切片只能在 O(1) 时间内从一个已经存在的数组创建;您在 ArraySlice has to create a copy of the sequence you pass in (O(n)) 上调用的初始化程序,并从它创建的中间数组中创建一个切片 (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?

完全正确。