[英]Swift Performance with instance property arrays
我遇到了一個有趣的Swift性能問題,正在尋找一些建議,分析為什么會發生這種情況。
我有一個算法,需要一個循環中成千上萬的數組訪問。 我發現如果將數組作為實例屬性引用(從同一類實例內部),則性能將非常差。 似乎在每次迭代時都取消引用該數組。 考慮到數組是工作的同一個類的成員,這似乎很奇怪。 self.x是否不需要一遍又一遍地取消對x的引用? 等效的Java代碼沒有相同的性能問題。
在下面的示例中,test3花費0.5秒,而test4花費0.15秒。
我真的必須遍歷所有代碼並在每次執行某項操作時分配本地范圍的數組嗎?
任何提示/想法都將受到歡迎。 我將編譯器優化設置為Fast-O。
西蒙
編輯:答案在本文的這篇文章中有詳細說明: https : //developer.apple.com/swift/blog/?id=27
希望能幫助到你。 長話短說,類范圍變量的私有/最終將消除不需要有害的間接訪問數組的需求。
class MyClass {
var array_1 = [Int64] (count: 16 , repeatedValue: 0)
var array_2 = [Int64] (count: 16 , repeatedValue: 0)
func runTest3() {
// test #3
//
let start = NSDate().timeIntervalSince1970
for i in 0 ... 10000000 {
if (array_1[ i%16 ] & array_2[ i%16 ] ) != 0 {
// whatever
}
}
let passed = NSDate().timeIntervalSince1970 - start
print("3 time passed: \(passed)")
}
func runTest4() {
// test #4
//
let start = NSDate().timeIntervalSince1970
let localArray_1 = self.array_1
let localArray_2 = self.array_2
for i in 0 ... 10000000 {
if (localArray_1[ i%16 ] & localArray_2[ i%16 ] ) != 0 {
// whatever
}
}
let passed = NSDate().timeIntervalSince1970 - start
print("4 time passed: \(passed)")
}
}
https://developer.apple.com/swift/blog/?id=27
類作用域變量的專用/最終消除了性能問題。 以上文章中的原因。 謝謝大家的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.