【发布时间】:2017-05-20 23:50:51
【问题描述】:
我一直在将我在 Java (Android) 中使用的算法移植到 Swift (iOS),并且在 Swift 版本上遇到了一些速度问题。
基本思想是存在具有深度的对象(评论树),我可以通过匹配隐藏对象列表来隐藏和显示来自数据集的回复。下面是一个可视化
Top
- Reply 1
- - Reply 2
- - Reply 3
- Reply 4
从数据集中隐藏后
Top
- Reply 1
- Reply 4
我从Java转换的相关方法如下
//Gets the "real" position of the index provided in the "position" variable. The comments array contains all the used data, and the hidden array is an array of strings that represent items in the dataset that should be skipped over.
func getRealPosition(position: Int)-> Int{
let hElements = getHiddenCountUpTo(location: position)
var diff = 0
var i = 0
while i < hElements {
diff += 1
if(comments.count > position + diff && hidden.contains(comments[(position + diff)].getId())){
i -= 1
}
i += 1
}
return position + diff
}
func getHiddenCountUpTo(location: Int) -> Int{
var count = 0
var i = 0
repeat {
if (comments.count > i && hidden.contains(comments[i].getId())) {
count += 1
}
i += 1
} while(i <= location && i < comments.count)
return count
}
这与 UITableViewController 一起使用以将 cmets 显示为树。
在 Java 中,使用 array.contains 足够快,不会造成任何延迟,但 Swift 版本在调用 heightForRowAt 和填充单元格时会多次调用 getRealPosition 函数,导致添加更多评论 ID 时会增加延迟到“隐藏”数组。
有什么方法可以提高数组“包含”查找的速度(可能使用不同类型的集合)?我对应用程序进行了分析,“包含”是占用时间最多的方法。
谢谢
【问题讨论】:
-
尝试使用
NSOrderedSet?我意识到这不是一种特别 Swift-y 的方法,但一个有序的集合是你想要的最大速度成员测试。或者,您可以尝试 this open-source implementation 的 SwiftOrderedSet。 -
问题不是
contains。我认为,问题在于您的数据模型对于您想要显示的数据以及您想要用它做什么是错误的。如果您不能立即掌握数据,那么您的数据模型就是错误的。
标签: arrays swift performance contains