在 Swift 中,空数组文字是否分配零容量用于存储?

问题描述 投票:0回答:1
let arr: [Int] = []

在这个实例中,Swift 是否没有分配任何缓冲区,因为数组文字是空的?

arrays swift
1个回答
0
投票

查看标准库的源代码,我们可以找到一个类,名为

__EmptyArrayStorage

/// Class used whose sole instance is used as storage for empty
/// arrays.  The instance is defined in the runtime and statically
/// initialized.  See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
///
/// NOTE: older runtimes called this _EmptyArrayStorage. The two must
/// coexist, so it was renamed. The old name must not be used in the new
/// runtime.
@_fixed_layout
@usableFromInline
@_objc_non_lazy_realization
internal final class __EmptyArrayStorage
  : __ContiguousArrayStorageBase {

因此仍然分配了一部分堆来存储

__EmptyArrayStorage
的这个实例,但所有空 Swift 数组将共享相同的存储空间。

© www.soinside.com 2019 - 2024. All rights reserved.