[SR-6693] Collection.underestimatedCount shouldn't call .count when the latter isn't O(1). #49242
Labels
bug
A deviation from expected or documented behavior. Also: expected but undesirable behavior.
standard library
Area: Standard library umbrella
Additional Detail from JIRA
md5: 1c211f9ba3face77d56f58149370eaa0
Issue Description:
Browsing the Collection source code at Apple's GitHub site, I noticed that the default implementation of Collection.underestimatedCount always forwards to .count. The "count" method is O👎 except when it's O(1) for random-access collections. Meanwhile, Sequence.underestimatedCount is supposed to be O(1).
So .underestimatedCount should forward to .count only for RandomAccessCollection. The wimpier, traversal-wise, Collection types should forward to .isEmpty instead. That keeps all Collection.underestimatedCount variants at O(1). Using .isEmpty limits the results of .underestimatedCount to 0 or 1, but that's OK since it's an under-estimate.
The text was updated successfully, but these errors were encountered: