Skip to content

Maps: Avoid double iteration in uniqueIndex for FilteredCollection#8197

Open
nickita-khylkouski wants to merge 1 commit intogoogle:masterfrom
nickita-khylkouski:fix/maps-uniqueindex-filtered-collection-6638
Open

Maps: Avoid double iteration in uniqueIndex for FilteredCollection#8197
nickita-khylkouski wants to merge 1 commit intogoogle:masterfrom
nickita-khylkouski:fix/maps-uniqueindex-filtered-collection-6638

Conversation

@nickita-khylkouski
Copy link
Contributor

Summary

  • Skip pre-sizing optimization in Maps.uniqueIndex when input is FilteredCollection or FilteredMultimapValues
  • Prevents double iteration since these classes have O(n) size() methods

Motivation

Maps.uniqueIndex calls size() on Collection inputs to pre-size the builder. However, FilteredCollection.size() and FilteredMultimapValues.size() iterate through all elements applying the predicate. This causes the predicate to be evaluated twice:

  1. Once during size() call
  2. Once during iteration to build the map

This fix skips the pre-sizing optimization for these filtered views, avoiding the double iteration.

Fixes #6638

Testing

  • Standalone test verified predicate is called once per element (4 calls), not twice (8 calls)
  • Basic functionality verified with normal collections

Skip pre-sizing optimization when input is FilteredCollection or
FilteredMultimapValues, as their size() methods iterate through all
elements, causing double iteration when combined with the subsequent
uniqueIndex iteration.

Fixes google#6638
@kluever kluever self-assigned this Feb 5, 2026
copybara-service bot pushed a commit that referenced this pull request Feb 5, 2026
…might be filtered on the fly.

Fixes #6638
Fixes #8197

RELNOTES=n/a
PiperOrigin-RevId: 866098324
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Consider avoiding the use of a pre-sized builder for the FilteredCollection in Maps#uniqueIndex

2 participants