为了运行测试代码,可以通过 Xcode→File→New→Project→command line tool 创建一个命令行程序工程,并新建一个任意名字的 swift 文件进行编辑开发。如果是在非 Mac 环境下通过 swift 命令行进行编译,可以编辑一个 swift 文件后,用 swiftc 命令行进行编译,如文件 main.swift,则编译命令为 swiftc main.swift,然后运行 ./main。
let arrayCount =10000000var array:[Int]=Array(repeating:0, count: arrayCount)for i in0..<array.count {
array[i]= i
}for method in["t1","t2","t3","t4"]{var dest:[Int]=[]let destCount =5000000let t1 =Date()print("engine = \(String(describing: method))")if method =="t1"{
dest =Array(repeating:0, count: destCount)for i in0..<destCount {
dest[i]= array[i]}}if method =="t2"{
dest = array[0..<destCount].map {$0}}elseif method =="t3"{
dest =Array(repeating:0, count: destCount)var i =0while i < destCount {
dest[i]= array[i]
i +=1}}elseif method =="t4"{
dest =Array(repeating:0, count: destCount)memcpy(&dest,&array, destCount*MemoryLayout<Int>.size)}let t2 =Date()print("time = \(t2.timeIntervalSince(t1))")print("index of \(1024) = \(dest[1024])")}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
现在可以一次性比较四种方法的性能差异,开始运行程序:
engine = t1
time =1.0509920120239258
index of 1024=1024
engine = t2
time =0.4606509208679199
index of 1024=1024
engine = t3
time =0.15001296997070312
index of 1024=1024
engine = t4
time =0.009117960929870605
index of 1024=1024
1
2
3
4
5
6
7
8
9
10
11
12
四、编译器优化
到目前为止,已经比较了四种方法在提取数组个数为 5000 万时的性能差异,但这真的就是“标准答案”吗?其实不尽然,因为 swift 编写的代码毕竟不是机器码,根据不同的编译器选项,它们编译生成的最终码也不相同,这里面自然会有很细微的差异,那么差异会有多大呢?
engine = t1
time =0.015030980110168457
index of 1024=1024
engine = t2
time =0.015980005264282227
index of 1024=1024
engine = t3
time =0.005139946937561035
index of 1024=1024
engine = t4
time =0.0037800073623657227
index of 1024=1024