[swift-users] AnySequence and type erasure

Dmitri Gribenko gribozavr at gmail.com
Thu Jun 23 04:27:38 CDT 2016

On Thu, Jun 23, 2016 at 2:12 AM, Svein Halvor Halvorsen
<svein.h at lvor.halvorsen.cc> wrote:
> 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?

You can't call '.count' on a Sequence without potentially consuming
the sequence.


(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-users mailing list