Swift 里 Array (二)初始化
init() 函数
在 Array 里
public init() {
_buffer = _Buffer()
}
以Buffer 是 _ContiguousArrayBuffer 为例。
即初始化了一个_ContiguousArrayBuffer。
在_ContiguousArrayBuffer里
/// Create an empty buffer.
@inlinable
internal init() {
_storage = _emptyArrayStorage
}
其中 _emptyArrayStorage 是一个__EmptyArrayStorage类的实例,对于所有的空数组,返回的都是同一个地址。
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
@inlinable
internal var _emptyArrayStorage : __EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
}
_swiftEmptyArrayStorage 定义如下:
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptyArrayStorage swift::_swiftEmptyArrayStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s19__EmptyArrayStorage), // isa pointer
},
// _SwiftArrayBodyStorage body;
{
0, // int count;
1 // unsigned int _capacityAndFlags; 1 means elementTypeIsBridgedVerbatim
}
};
init(repeatedValue, count) 方法
根据元素类型,初始化_ContiguousArrayStorage类,并在堆上空间,类的尾部分配若干内存,用于存储元素。
然后使用传入的value,从头初始化内存。
public init(repeating repeatedValue: Element, count: Int) {
var p: UnsafeMutablePointer<Element>
(self, p) = Array._allocateUninitialized(count)
for _ in 0..<count {
p.initialize(to: repeatedValue)
p += 1
}
}
internal static func _allocateUninitialized(
_ count: Int
) -> (Array, UnsafeMutablePointer<Element>) {
let result = Array(_uninitializedCount: count)
return (result, result._buffer.firstElementAddress)
}
init<S: Sequence>(_ s: S) 方法
public init<S: Sequence>(_ s: S) where S.Element == Element {
self = Array(
_buffer: _Buffer(
_buffer: s._copyToContiguousArray()._buffer,
shiftedToStartIndex: 0))
}
把Sequence 转为ContiguousArray,然后再转为Array。
internal func _copySequenceToContiguousArray<
S : Sequence
>(_ source: S) -> ContiguousArray<S.Element> {
let initialCapacity = source.underestimatedCount
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>(
initialCapacity: initialCapacity)
var iterator = source.makeIterator()
// FIXME(performance): use _copyContents(initializing:).
// 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)
}
return builder.finish()
}
其中用到了Sequence 的iterator。
在遍历过程中,可能会存在内存不够,需要重新分配内存。
/// Add an element to the buffer, reallocating if necessary.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func add(_ element: Element) {
if remainingCapacity == 0 {
// Reallocate.
let newCapacity = max(_growArrayCapacity(result.capacity), 1)
var newResult = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCapacity, minimumCapacity: 0)
p = newResult.firstElementAddress + result.capacity
remainingCapacity = newResult.capacity - result.capacity
if !result.isEmpty {
// This check prevents a data race writting to _swiftEmptyArrayStorage
// Since count is always 0 there, this code does nothing anyway
newResult.firstElementAddress.moveInitialize(
from: result.firstElementAddress, count: result.capacity)
result.count = 0
}
(result, newResult) = (newResult, result)
}
addWithExistingCapacity(element)
}
分配内存时,大小是指数级增长。
@inlinable
internal func _growArrayCapacity(_ capacity: Int) -> Int {
return capacity * 2
}
Swift 里 Array (二)初始化的更多相关文章
- Swift 里 Array (一)内存结构
public struct Array<Element>: _DestructorSafeContainer { #if _runtime(_ObjC) @usableFromInline ...
- Swift 里 Array (四) Accessing Elements
根据下标取值 关键代码如下: func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _ ...
- Swift 里 Array (三) Inspecting an Array
判断是否为空 使用的是Collection协议里isEmpty的判断. public var isEmpty: Bool { return startIndex == endIndex } start ...
- swift学习(二)--基本运算符、字符串、集合操作
在这一篇博客里面,我想要介绍一下swift里面一些常用的基本运算符,还有涉及到的字符串,集合操作.你会发现在swift里面还是有许多其他语言所不具有的特性运算操作的. 首先最基本的+,-,*,/,&g ...
- [Swift]数组(Array)最强解析
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- Swift中文教程(二)--简单值
原文:Swift中文教程(二)--简单值 Swift使用let关键字声明常量,var关键字声明变量.常量无需在编译时指定,但至少要被赋值一次.也就是说,赋值一次多次使用: var myVariable ...
- Swift里performSelector方法的替代
最近在回答StackOverflow的问题时,发现performSelector方法在Swift被去掉,Apple的注释是这个方法被去掉是因为不安全: NOTE The performSelector ...
- Swift 学习之二十一:?和 !(详解)
http://blog.csdn.net/woaifen3344/article/details/30244201 Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始 ...
- iOS开发Swift篇—(二)变量和常量
iOS开发Swift篇—(二)变量和常量 一.语言的性能 (1)根据WWDC的展示 在进行复杂对象排序时Objective-C的性能是Python的2.8倍,Swift的性能是Python的3.9倍 ...
随机推荐
- 第15章 上下文管理器和else块
#<流流畅的Python>第15章 上下文管理器和else块 #15.1 先做这个,再做那个:if语句之外的else块 #else子句不仅能在if语句中使用,还能在for.while和tr ...
- Javascript、Jquery获取浏览器和屏幕各种高度宽度(单位都为px)
Javascript.Jquery获取浏览器和屏幕各种高度宽度 另外参见 http://www.cnblogs.com/top5/archive/2009/05/07/1452135.html ...
- IntellJ IDEA2017 springboot2.0.2 替代@SpringBootApplication方式
如果不想用@SpringBootApplication,那么可以用@EnableAutoConfiguration 和@ComponentScan替代@SpringBootApplication 详情 ...
- vue中文章的折叠于显示全部
在以一篇文章中,可能文章特别长,但是在页面第一次显示的时候可能就只需要显示一部分,这种情况下就需要自己进行修改 基本思路 利用类名就是预先定义一个类名,设置高度,和overflow:hidden,前提 ...
- 第26章:MongoDB-索引
①索引 索引本质上是树,最小的值在最左边的叶子上,最大的值在最右边的叶子上,使用索引可以提高查询速度(而不用全表扫描),也可以预防脏数据的插入(如唯一索引). 索引通常能够极大的提高查询的效率,如果没 ...
- php 爬虫简单示例
<?php error_reporting(E_ALL^E_NOTICE^E_WARNING); $url = "http://cp.360.cn/ssccq/?menu&r_ ...
- Redis-4.0.11集群配置
版本:redis-3.0.5 redis-3.2.0 redis-3.2.9 redis-4.0.11 参考:http://redis.io/topics/cluster-tutorial. 集群 ...
- git使用教程(初次配置+错误提示)
初次使用配置目录:https://blog.csdn.net/Esc_Tab_End/article/details/84144063 error: RPC failed; curl 56 OpenS ...
- sys/time.h 和 time.h
今天在燕麦工作第二天.看荣哥给我的程序,发现程序里面用的延时跟我以前使用的不同.导入两个头文件,然后用函数来获得时间.关于这个函数特别查来一下. time.h 是ISO C99 标准日期头文件. s ...
- java基础-day26
第03天 java基础加强 今日内容介绍 u BeanUtils概述及使用 u XML简介及约束 u XML解析 第1章 XML简介 1.1 XML基本语法 1.1.1 XML概述 XML全称为 ...