[swift-users] AnySequence and type erasure

Svein Halvor Halvorsen svein.h at lvor.halvorsen.cc
Thu Jun 23 04:12:24 CDT 2016


2016-06-18 10:23 GMT+02:00 Dmitri Gribenko <gribozavr at gmail.com>:

> On Fri, Jun 17, 2016 at 12:37 PM, Svein Halvor Halvorsen
> <svein.h at lvor.halvorsen.cc> wrote:
> > Ok. Good to hear that I'm not too far off :)
> >
> > Can you provide me with an example of a sequence type or two that has
> some
> > map or other function that would benefit from an optimized wrapper? Or:
> > under what circumstances would the stdlib implementation outperform mine?
>
> Compare the default implementations of map() for Sequence and
> Collection.  In the Sequence case, we don't know the size of the
> resulting array, so we have to grow the resulting array as we pull the
> elements from the sequence.  In the case of running Collection.map()
> we know the final size from the count property.  In the case of Array
> we can do even better and eliminate a check (the _expectEnd()
> call).  However, certain collections where calculating the number of
> elements might be expensive, can opt into the Sequence behavior (e.g.,
> various string views); this is up to the designer of the specific
> collection.


Is this a problem in reality? The map() on Sequence uses
underestimatedCount to reserve capacity, and if the sequence wraps a
collection type, underestimatedCount is presumably O(1) and returns the
same value as count, non?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160623/85a3a256/attachment.html>


More information about the swift-users mailing list