在Swift中将字符串转换为数组的时间复杂度是多少,也就是:数组(“abc”)。是O(n)还是Swift使用某种类型的内部机制来优化它,因为String符合序列协议。
从序列协议的角度来考虑这个问题是对的。但是sequence
实际上就需求而言非常简单,并且没有提供比O(n)更好的方法-迭代器机制在IteratorProtocol的文档中描述。
要想了解这一点的作用,可以在下面找到关键的源代码:
@inlinable
public init<S: Sequence>(_ s: S) where S.Element == Element {
self = Array(
_buffer: _Buffer(
_buffer: s._copyToContiguousArray()._buffer,
shiftedToStartIndex: 0))
}
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(iterator.next()!)
}
// Add remaining elements, if any.
while let element = iterator.next() {
builder.add(element)
}