Why is for-in slower than while in swift debugging mode?
I wrote this.
Thanks for people who answer to me, I could have learned Seqeunce
and IteratorProtocol
.
So I implemented custom type ( School
below code ) which conformed Sequence
.
And I checked Xcode-time profile.
But I can't find anything protocol witness
But If only use range
and for-in
, time profiler show protocol witness.
why is indexingIterator.next()
using dynamic method but not in School
?
I thought that even struct
conformed protocol
, if variable in struct
type use method of protocol
, this method will be static method. If I am wrong, Could you please tell me what is wrong?
⬇️School
code
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
is not dynamically dispatched - the methods thatIndexingIterator.next
calls, such asCollection.formIndex
, are. That's why you don't see a protocol witness fornext
, only ones forformIndex
,subscript
etc. – Rhinitis