Swift 里 Array (一)内存结构

public struct Array<Element>: _DestructorSafeContainer {
  #if _runtime(_ObjC)
  @usableFromInline
  internal typealias _Buffer = _ArrayBuffer<Element>
  #else
  @usableFromInline
  internal typealias _Buffer = _ContiguousArrayBuffer<Element>
  #endif

  @usableFromInline
  internal var _buffer: _Buffer
}

Array 是一个结构体。先看 runtime 不是 Objc 的情况。

Swift Array

runtime Objc 情况

内存结构

Array 是一个结构体,持有了一个类_ContiguousArrayStorage
类其中只有一个结构体_ArrayBody, 其中存储了数组的长度和分配的内存大小。
在初始化时,会在分配好的内存的尾部,附加分配一些内存,存储数组中的数据。

_storage = Builtin.allocWithTailElems_1(
 _ContiguousArrayStorage<Element>.self,
 realMinimumCapacity._builtinWordValue, Element.self)

Array 所有的操作,基本上都是基于_ContiguousArrayStorage 的。
其中一个函数,可以确定是否还有其他人引用当前的_ContiguousArrayStorage。在修改数组时,需要确定是否需要 copy 所有元素,这个函数十分重要。

  /// Returns `true` iff this buffer's storage is uniquely-referenced.
  ///
  /// - Note: This does not mean the buffer is mutable.  Other factors
  ///   may need to be considered, such as whether the buffer could be
  ///   some immutable Cocoa container.
  @inlinable
  internal mutating func isUniquelyReferenced() -> Bool {
    return _isUnique(&_storage)
  }

posted on 2019-03-20 22:02  花老🐯  阅读(600)  评论(0编辑  收藏  举报

导航