xueyin87 / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

consider memoizing results of filtering a lazily filtered Iterable #314

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
consider this snippet:

    return ImmutableSet.copyOf(Sets.filter(
        unfilteredSetOfThings,
        new Predicate<Thing>() {
          @Override
          public boolean apply(Thing thing) {
            return thing.isAcceptable();
          }
        }));

Q1:
  how many times is "isAcceptable" invoked on each Thing in the list of 
unfiltered Things?

Q2:
  how many times would you think it should be invoked?

For me, A2 was 1; alas, A1 disagreed!

In short, each Thing has "isAcceptable" invoked 3 times for this one 
copyOf() operation.  This happens each time .size() is called on the filtered 
view of the unfitered set, and then once while iterating.

Filing to solicit opinions on whether this is ok behavior.

thanks
-Fred

Original issue reported on code.google.com by ffa...@gmail.com on 15 Jan 2010 at 4:53

GoogleCodeExporter commented 9 years ago
The documentation clearly states that the XXX.filter are views. So they have to 
be
called as many times as needed.

Quoting the doc: "Many of the filtered set's methods, such as size(), iterate 
across
every element in the underlying set and determine which elements satisfy the 
filter.
When a live view is not needed, it may be faster to copy 
Iterables.filter(unfiltered,
predicate) and use the copy."

If you need it to be called only once, consider using Iterables.filter instead 
of
Sets.filter.

Original comment by ogregoire on 15 Jan 2010 at 9:57

GoogleCodeExporter commented 9 years ago
Indeed so, thank you. This issue should be marked WAI now.

Original comment by ffa...@gmail.com on 15 Jan 2010 at 10:03

GoogleCodeExporter commented 9 years ago

Original comment by kevinb@google.com on 15 Jan 2010 at 9:13

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:16

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:10