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倍 ...
随机推荐
- 初识python函数
一.函数 1.什么是函数 函数是对功能或者动作的封装 2.函数的语法和定义 def 函数名(): 函数体 调用: 函数名() 3.关于函数的返回值 return : 返回 1.当程序没写过retur ...
- samba服务和nginx服务
一 samba服务 1 samba的功能:samba是一个网络服务器,是连接linux和windows之间共享文件的. 2 samba服务的启动,停止和重启: (1) 要启动Samba服务,只需用户 ...
- mysql 数据插入优化方法(concurrent_insert=2)
当一个线程对一个表执行一个DELAYED语句时,如果不存在这样的处理程序,一个处理器线程被创建以处理对于该表的所有DELAYED语句.通常来说,在MyISAM里读写操作是串行的,但当对同一个表进行查询 ...
- 2018.12.05 codeforces 961E. Tufurama(主席树)
传送门 一眼主席树sbsbsb题(%%%树状数组大佬们). 简化题意:求满足x<y,y≤ax,x≤ayx<y,y\le a_x,x\le a_yx<y,y≤ax,x≤ay的(x, ...
- math.net 拟合
参考:http://blog.csdn.net/ztmsimon/article/details/50524392 在论坛中总看到有人在说Math.NET Iridium,查了一下,现在被整合到Mat ...
- c#内存中创建反射
代码 IWFP_SYS_Bytes mywfpbyte; /**/ byte[] bin=null; using (FileStream fs = new FileStream(filename, F ...
- tomcat部署项目访问不加项目名方法
直接主题:tomcat部署项目访问不加项目名方法是打开tomcat的conf目录下server.xml文件 加入 <Context path="" docBase=" ...
- 理解shell的eval命令
看以下两条命令:[zhangsan@XEN /sys]$ a="ls";b="\$a";c="$b";"$c"Hey! ...
- set_time_limit
语法 : void set_time_limit (int seconds)说明 : 设定一个程式所允许执行的秒数,如果到达限制的时间,程式将会传回错误.它预设的限制时间是30秒,max_execut ...
- set_error_handler
set_error_handler这个函数的作用是为了防止错误路径泄露 何为错误路径泄露呢? 我们写程序,难免会有问题,而PHP遇到错误时,就会给出出错脚本的位置.行数和原因 有很多人说,这并没有什么 ...