[swift-dev] Implementation of Existential Collection (AnySequence and co.)
pali at pali.sk
Wed Apr 5 07:56:29 CDT 2017
On Wednesday, 5 April 2017 at 11:59, Ole Begemann wrote:
> On 05.04.2017 00:33, Pavol Vaskovic via swift-dev wrote:
> > ## Abstract Base Class with Single Concrete Implementation
> > What is the purpose of having an internal abstract base `class _AnyIteratorBoxBase`, that is only inherited by the `internal final class _IteratorBox`?  It is used as the type to store the underlying base in the `struct AnyIterator`, but the initializers in `AnyIterator` create only concrete instances of `_IteratorBox` and the remaining occurrence of `_AnyIteratorBoxBase` is as parameter for `internal init` that isn’t used anywhere. My search found no other subclasses of `_AnyIteratorBoxBase`, so I guess this is not an extension point.
> This is not an answer to your performance questions, but I believe I can
> explain why the `_AnyIteratorBoxBase` base class is needed.
> The purpose of `AnyIterator<Element>` is to hide the specific type of
> the iterator it wraps. Hence it can't have a property whose type is
> generic over the iterator type `I` (because then `AnyIterator` would
> have to be generic over `I` too). Hence `AnyIterator` can't have a
> property `let _box: _IteratorBox<I>` directly.
> Here's where the base class comes in. `_AnyIteratorBoxBase` is _not_
> generic over `I` and thus erases the iterator type. Only the initializer
> must be generic over `I` because it's the only place that needs to
> handle the concrete `_IteratorBox<I>` type.
Thanks Ole! This explanation of type erasure makes total sense. I have overlooked they are generic over different axis.
But I think I have confirmed the performance implications of this design and created https://bugs.swift.org/browse/SR-4499 to track the issue.
As is, all elements that get vended through this are being created using virtual dispatch on generic protocol - super slow.
If I recall correctly, there is alternative approach to type erasure using closures, but its possible it has similar performance characteristics?
Does this show a need for a different approach to type erasure in Swift? Some language or compiler support?
More information about the swift-dev