加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 里 Array (一)内存结构

发布时间:2020-12-14 05:00:17 所属栏目:百科 来源:网络整理
导读:public struct ArrayElement: _DestructorSafeContainer { #if _runtime(_ObjC) @usableFromInline internal typealias _Buffer = _ArrayBufferElement #else @usableFromInline internal typealias _Buffer = _ContiguousArrayBufferElement #endif @usable
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)
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读