[swift-dev] [swift-users] Collection underestimatedCount() does _?

Will Stanton willstanton1 at yahoo.com
Sat Mar 19 18:04:43 CDT 2016


Hello Brent,

Thanks for pointing it out - obvious now!

Regards,
Will Stanton

> On Mar 19, 2016, at 6:43 PM, Brent Royal-Gordon via swift-dev <swift-dev at swift.org> wrote:
> 
> Actually, the code samples I gave you *do* subtly depend on underestimatedCount being an underestimate, because the initial fast loop force-unwraps the element returned by `next`. If the count is an overestimate, that force unwrap will fail. You can see it in my example:
> 
> 			// Load all the fast elements
> 			for _ in 0..<fastCount {
> 				let elem = generator.next()!
> 				_appendElementQuicklyBecauseWeAlreadyKnowWeHaveTheCapacity(elem)
> 			}
> 
> And in the actual standard library code:
> 
> 	  // Add elements up to the initial capacity without checking for regrowth.
> 	  for _ in 0..<initialCapacity {
> 	    builder.addWithExistingCapacity(generator.next()!)
> 	  }
> 
> These and similar constructs could be turned into `if let`s, but that would add a conditional branch which would make the loop slower, particularly in -Ounchecked mode where safety checks are disabled. In that mode, the force unwrap operator simply *assumes* the value is not `nil`, which makes this code run as fast as possible—it pretty much can just copy or retain the element, assign it into the next slot in the array, and increment the array's count.



More information about the swift-dev mailing list