提问者:小点点

Swift中字符串到数组的转换:时间复杂度


在Swift中将字符串转换为数组的时间复杂度是多少,也就是:数组(“abc”)。是O(n)还是Swift使用某种类型的内部机制来优化它,因为String符合序列协议。


共1个答案

匿名用户

从序列协议的角度来考虑这个问题是对的。但是sequence实际上就需求而言非常简单,并且没有提供比O(n)更好的方法-迭代器机制在IteratorProtocol的文档中描述。

要想了解这一点的作用,可以在下面找到关键的源代码:

  1. https://github.com/apple/swift/blob/main/stdlib/public/core/array.swift
  @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)
  }