[swift-dev] Implementation of Type Erasers
Chris Eidhof
chris at eidhof.nl
Mon Sep 5 13:13:03 CDT 2016
Hello swift-dev,
I was wondering why type erasers (e.g. for AnyIterator) are implemented the
way they are. I would implement AnyIterator like this:
final class MyAnyIterator<A>: IteratorProtocol {
var nextImpl: () -> A?
init<I: IteratorProtocol>(iterator: I) where I.Element == A {
var copy = iterator
nextImpl = { copy.next() }
}
func next() -> A? {
return nextImpl()
}
}
Instead, it is implemented in a class which contains a box. The trick with
subclassing and generics to actually erase the type feels like a bit of a
hack, but I figured it would be there for performance reasons. In my
limited testing, I noticed my version is 20% slower when compiling without
optimizations. I didn't really understand why, even after reading through
the SIL. However, when compiling with optimizations, I noticed my version
is 10% faster.
I would like to make a PR to change the stdlib, but before I go through the
hassle, I'd like to hear what the reasons (at the time?) were for the
current solution. Maybe it's just that the optimizer got better?
Thanks!
(Apologies if you receive this mail twice, my first message bounced saying
it was waiting for moderator approval, it didn't seem to get approved)
--
Chris Eidhof
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20160905/2ccc2357/attachment.html>
More information about the swift-dev
mailing list