I'm using the underestimatedCount
computed property of sequences to reserve capacity of a container before operations such as map
. The underestimatedCount
is used in the same way in the standard library, such as the Array
initializer that use a sequence as input:
let sequence = [1, 2, 3]
let result = Array(sequence) // Internally use `underestimatedCount`
// to avoid reallocatinons
Some sequences forward the underestimatedCount
, such as LazySequence
:
let seq = [1, 2, 3].lazy
print(seq.underestimatedCount) // Prints '3'
Moreover, the Collection
default implementation is the collection's count
value, so a ReversedCollection
forward the underestimatedCount
automatically:
let seq = [1, 2, 3].reversed()
print(seq.underestimatedCount) // Prints '3'
However, I found that some sequences does not forward the underestimatedCount
such as:
let seq = [1, 2, 3].enumerated()
print(seq.underestimatedCount) // Prints '0'
And some other combinations neither:
let seq = [[1, 2], [3]].lazy.joined()
print(seq.underestimatedCount) // Prints '0', removing `lazy` prints `3`
Is this intended behavior? This could lead to poorly efficient code causing many unnecessary array reallocations.