如何使用Swift(beta)Array击败NSMutableArray的性能? [英] How to beat NSMutableArray performance with Swift (beta) Array?

查看:92
本文介绍了如何使用Swift(beta)Array击败NSMutableArray的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我试图建立大量的项目集合。当在CoreData on-the-go中创建元素时,这是非常快速的。但是,当尝试保留这些项目的索引时,创建数组Swift具有很大的性能影响。下面的代码是NSMutableArray和Swift数组之间的基准。当在iOS模拟器中运行时,Swift数组大约慢8倍。为什么这是可以改进,还是应该改进,因为苹果发布新的Xcode / Swift版本?

In Swift, I'm trying to build a large collection of items. When creating elements in CoreData on-the-go, this is very speedy. However when trying to keep an index to those items, creating an array Swift has a large performance impact. The code below is a benchmark between NSMutableArray and Swift's Array. When ran in the iOS Simulator, the Swift Array is around 8x slower. Why is this, can it be improved, or should it improve over the as Apple releases new builds of Xcode/Swift?

代码:

var start: NSDate
var time: NSTimeInterval
var batch = 1000000
var rate: Double

var oArr = NSMutableArray(capacity: batch)
start = NSDate()
for i in 1..batch {
    oArr.addObject(i)
}
time = -start.timeIntervalSinceNow
rate = Double(batch) / Double(time)
println("NSMutableArray \(batch) appends in \(time) sec: \(rate)/sec")

var sArr = Int[]()
start = NSDate()
for i in 1..batch {
    sArr += i
}
time = -start.timeIntervalSinceNow
rate = Double(batch) / Double(time)
println("Array<Int>     \(batch) appends in \(time) sec: \(rate)/sec")

NSMutableArray 1000000 appends in 1.17320102453232 sec: 852368.843096295/sec
Array<Int>     1000000 appends in 9.31138801574707 sec: 107395.374170729/sec

在模拟器中输出(beta 3):

Output in simulator (beta 3):

NSMutableArray 1000000 appends in 0.71416300535202 sec: 1400240.55083487/sec
Array<Int>     1000000 appends in 5.00839000940323 sec: 199664.961818569/sec



iPhone5上的输出(iOS 7.1上的beta 3)

Output on iPhone 5 (beta 3 on iOS 7.1):

NSMutableArray 1000000 appends in 8.79256194829941 sec: 113732.494110367/sec
Array<Int>     1000000 appends in 55.6573320031166 sec: 17967.084730975/sec


推荐答案

更新:

使用Xcode beta-3,在MacBook Pro 2 GHz Intel Core i7上使用控制台程序, (由于较小的语法变化,也是固定语法):

with Xcode beta-3, with a console program on a MacBook Pro 2 GHz Intel Core i7, I get these numbers with the original test (also fixed syntax due to minor grammar changes):

调试(-O0):

NSMutableArray 1000000 appends in 0.782136023044586 sec: 1278549.9843203/sec
Array<Int>     1000000 appends in 5.56463801860809 sec: 179706.208500177/sec

发布>

Release (-Os):

NSMutableArray 1000000 appends in 0.14977502822876 sec: 6676680.43081684/sec
Array<Int>     1000000 appends in 0.124498963356018 sec: 8032195.3937913/sec

发布>

Release (-Ofast):

NSMutableArray 1000000 appends in 0.151567995548248 sec: 6597698.91646863/sec
Array<Int>     1000000 appends in 0.122538030147552 sec: 8160731.80543105/sec

这篇关于如何使用Swift(beta)Array击败NSMutableArray的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆