Swift 里 Array (一)内存结构

博客主要介绍了Swift Array相关内容。先探讨了runtime非Objc的情况,接着分析了runtime Objc情况。指出Swift Array是结构体,持有一个类,类中有结构体存储数组长度和分配内存大小,初始化时会在内存尾部附加存储数据,还提到一个确定引用情况的重要函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
  }

转载于:https://www.cnblogs.com/huahuahu/p/Swift-li-Array-yi-nei-cun-jie-gou.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值