<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body dir="auto"><div>On Mar 19, 2016, at 2:53 PM, Brent Royal-Gordon via swift-users &lt;<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>&gt; wrote:</div><div><br></div><blockquote type="cite"><div><blockquote type="cite"><blockquote type="cite"><span>I might have missed something since a lot of the results are for tests &lt;<a href="https://github.com/apple/swift/search?utf8=✓&amp;q=underestimatedCount&amp;type=Code">https://github.com/apple/swift/search?utf8=✓&amp;q=underestimatedCount&amp;type=Code</a>&gt;</span><br></blockquote></blockquote><blockquote type="cite"><blockquote type="cite"><span>But why would `underestimatedCount` ever be used instead of `count`? Don’t most collections have O(1) `count` anyway?</span><br></blockquote></blockquote><blockquote type="cite"><span></span><br></blockquote><blockquote type="cite"><span>Hi Will,</span><br></blockquote><blockquote type="cite"><span></span><br></blockquote><blockquote type="cite"><span>This API comes from Sequence, which does not have a count that you can</span><br></blockquote><blockquote type="cite"><span>inspect without possibly consuming the sequence.</span><br></blockquote><span></span><br><span>To add some color:</span><br><span></span><br><span>A sequence merely says that it has a bunch of elements and you can walk through them. It does *not* promise several important things:</span><br><span></span><br><span>* That you can get the elements in the sequence more than once</span><br><span>* That it knows the number of elements in the sequence and can quickly return them</span><br><span>* That you can get the number of elements in the sequence without walking through and counting them one by one</span><br><span></span><br><span>This adds up to an ugly conclusion: With just a sequence, it is impossible to efficiently discover the count, and doing so might destroy the sequence.</span><br><span></span><br><span>That's obviously not so great. In particular, it's not so great when you want to load a sequence into an array. The simple, naive way is to do this:</span><br><span></span><br><span> &nbsp; &nbsp;// Notionally</span><br><span> &nbsp; &nbsp;struct Array&lt;Element&gt; {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;init&lt;Seq: SequenceType where Seq.Generator.Element == Element&gt;(_ seq: Seq) {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.init()</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for elem in seq {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;appendElement(elem)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp;}</span><br><span></span><br><span>But this may resize the array several times, which would be very slow. The fastest way to do that will be to pre-allocate the exact right number of elements so you don't have to keep resizing the array:</span><br><span></span><br><span> &nbsp; &nbsp;// Notionally</span><br><span> &nbsp; &nbsp;struct Array&lt;Element&gt; {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;init&lt;Seq: SequenceType where Seq.Generator.Element == Element&gt;(_ seq: Seq) {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.init()</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;reserveCapacity(seq.count)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for elem in seq {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_appendElementQuicklyBecauseWeAlreadyKnowWeHaveTheCapacity(elem)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp;}</span><br><span></span><br><span>But `seq.count` might consume the sequence, leaving you unable to add any elements. What do we do?</span><br><span></span><br><span>Enter `underestimateCount()`. We can always call `underestimateCount()` and size to whatever it says we should be. For sequences with easily-calculated counts, this should give us a size that's just right. For sequences where they can kind of estimate the right count (for instance, if you're decoding a fixed-size buffer of UTF-8 bytes, and you know how many bytes there are but not exactly how many characters they'll decode to), it will get us at least part of the way there. For sequences whose size is completely unknown, it won't help but it won't hurt much either.</span><br><span></span><br><span>So you do this:</span><br><span></span><br><span> &nbsp; &nbsp;// Notionally</span><br><span> &nbsp; &nbsp;struct Array&lt;Element&gt; {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;init&lt;Seq: SequenceType where Seq.Generator.Element == Element&gt;(_ seq: Seq) {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.init()</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let fastCount = seq.underestimateCount()</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;reserveCapacity(fastCount)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// We'll have to pull elements out manually.</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let generator = seq.generate()</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Load all the fast elements</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for _ in 0..&lt;fastCount {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let elem = generator.next()!</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_appendElementQuicklyBecauseWeAlreadyKnowWeHaveTheCapacity(elem)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Get anything else that's left</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while let elem = generator.next() {</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;appendElement(elem)</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp;}</span><br><span></span><br><span>(If you're looking at Swift 3, remember: SequenceType is now Sequence, Generator is now Iterator, generate() is now makeIterator(), and underestimateCount() is now underestimatedCount().)</span><br><span></span><br><span>And in fact, this is quite similar to some real source code inside Array:</span><br><span></span><br><span> &nbsp; &nbsp;@warn_unused_result</span><br><span> &nbsp; &nbsp;internal func _copySequenceToNativeArrayBuffer&lt;</span><br><span> &nbsp; &nbsp; &nbsp;S : SequenceType</span><br><span> &nbsp; &nbsp;&gt;(source: S) -&gt; _ContiguousArrayBuffer&lt;S.Generator.Element&gt; {</span><br><span> &nbsp; &nbsp; &nbsp;let initialCapacity = source.underestimateCount()</span><br><span> &nbsp; &nbsp; &nbsp;var builder =</span><br><span> &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;_UnsafePartiallyInitializedContiguousArrayBuffer&lt;S.Generator.Element&gt;(</span><br><span> &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;initialCapacity: initialCapacity)</span><br><span> &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp;var generator = source.generate()</span><br><span> &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp;// FIXME(performance): use _initializeTo().</span><br><span> &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp;// Add elements up to the initial capacity without checking for regrowth.</span><br><span> &nbsp; &nbsp; &nbsp;for _ in 0..&lt;initialCapacity {</span><br><span> &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;builder.addWithExistingCapacity(generator.next()!)</span><br><span> &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp;// Add remaining elements, if any.</span><br><span> &nbsp; &nbsp; &nbsp;while let element = generator.next() {</span><br><span> &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;builder.add(element)</span><br><span> &nbsp; &nbsp; &nbsp;}</span><br><span> &nbsp; &nbsp;</span><br><span> &nbsp; &nbsp; &nbsp;return builder.finish()</span><br><span> &nbsp; &nbsp;}</span><br><span></span><br><span>Now, collections *do* promise that you can walk through a sequence more than once, and some collections (ones that promise "random access") promise that `count` can be calculated quickly. But because CollectionType conforms to SequenceType, some code may receive a collection but only know it's a sequence. Fortunately, the standard library provides a default implementation of `underestimateCount` for collections:</span><br><span></span><br><span> &nbsp; &nbsp; &nbsp;public func underestimateCount() -&gt; Int {</span><br><span> &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;return numericCast(count)</span><br><span> &nbsp; &nbsp; &nbsp;}</span><br><span></span><br><span>So you just don't have to worry about this on collections. Implement `count` and `understimateCount` will take care of itself.</span><br><br></div></blockquote><br><div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">Okay, so… maybe I am unfairly treating your summary as the whole story… returning to the example of the contents of /dev/random, or quadrature data from a wireless receiver, which are supposed to be neither finite nor reproducible, but are indisputably one-thing-after-another — sequences in the common sense of the word …</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">Am I to gather</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">1: that the standard API <i>requires</i> that&nbsp;</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">every Sequence type can be instantiated so as to replicate the contents of another? The whole value of Sequence to the examples is that it should be impossible.&nbsp;</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">2:&nbsp;that the standard API <i>requires</i> of every Sequence that it should serve the expectation of the supposedly-uncoupled API of Array that it is free to buffer the entire contents of any Sequence of the same Element? Need it or not? B</span><span style="background-color: rgba(255, 255, 255, 0);">ad news for memory and performance.</span></div></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">The answer may be that if the user knows enough to build a Sequence for which laziness is indispensable, she should have better sense than to rely on those two things, required or not.</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">But a lifetime of Law and debugging have given me an exceptionally dirty mind. If those really are API, I can avoid them, but I can't expect others — including the standard library — to.</span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div id="AppleMailSignature"><span style="background-color: rgba(255, 255, 255, 0);">&nbsp; &nbsp; — F</span></div><div><br></div></body></html>