【发布时间】:2021-07-06 00:33:21
【问题描述】:
Why is for-in slower than while in swift debugging mode?
我写了这个。
感谢回答我的人,我本可以学习Seqeunce 和IteratorProtocol。
所以我实现了符合Sequence 的自定义类型(代码下方的School)。
我检查了 Xcode-time 配置文件。
但如果只使用 range 和 for-in ,时间分析器会显示 protocol witness。
为什么 indexingIterator.next() 使用 动态方法 而不是 School ?
我认为即使struct符合protocol,如果struct中的变量类型使用protocol的方法,该方法将是静态方法。如果我错了,你能告诉我哪里错了吗?
⬇️School代码
struct SchoolIterator: IteratorProtocol {
private var schoolList: School
var idx = 0
init(_ school: School) {
self.schoolList = school
}
mutating func next() -> String? {
defer { idx += 1 }
guard schoolList.count-1 >= idx
else { return nil }
return schoolList[idx]
}
}
struct School: Sequence {
fileprivate var list = Array(repeating: "school", count: 100000)
var count: Int { return list.count }
subscript(_ idx: Int ) -> String? {
guard idx <= count-1
else { return nil }
return list[idx]
}
func makeIterator() -> SchoolIterator {
return SchoolIterator(self)
}
}
var schools = School()
for school in schools {
print(school)
}
【问题讨论】:
-
糟糕,您发现我的措辞有误。
IndexingIterator.next不是动态调度的——IndexingIterator.next调用的方法,例如Collection.formIndex,是。这就是为什么您看不到next的协议见证,只有formIndex、subscript等的协议见证。 -
@Sweeper 非常感谢!我现在可以理解问题所在了。即使今天是周末,你也回复了我。我真的很感激你。
标签: swift for-loop compilation iterator dynamic-dispatch