Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
oksana-evs opened this issue Jul 14, 2023 · 1 comment

Comments

@oksana-evs
Copy link

oksana-evs commented Jul 14, 2023

If values is a Collection, a presized builder is used in Maps#uniqueIndex (the change was introduced in this commit)

  @CanIgnoreReturnValue
  public static <K, V> ImmutableMap<K, V> uniqueIndex(
      Iterable<V> values, Function<? super V, K> keyFunction) {
    if (values instanceof Collection) {
      return uniqueIndex(
          values.iterator(),
          keyFunction,
          ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size()));
    }
    return uniqueIndex(values.iterator(), keyFunction);
  }

However, for FilteredCollection, calling size() results in applying the predicate to all the elements of the unfiltered collection (link)

    @Override
    public int size() {
      int size = 0;
      for (E e : unfiltered) {
        if (predicate.apply(e)) {
          size++;
        }
      }
      return size;
    }

To prevent applying the predicate an additional time , presized builder should not be used if values is a FilteredCollection or FilteredMultimapValues

@oksana-evs
Copy link
Author

The suggested fix is implemented in this pull request: PicnicSupermarket#27

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants
@lowasser @eamonnmcmanus @oksana-evs and others