Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8067969

Optimize Stream.count for SIZED Streams

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P5 P5
    • 9
    • 8, 9
    • core-libs

        Requesting 'count' on a SIZED Stream (like the result of Collection.stream or Arrays.stream) apparently triggers a linear traversal of the stream, even though the Stream already knows its size. This could fairly easily be optimized.

        This isn't very useful for self-contained use cases (why not just get the size directly?), but comes up when you pass Stream or Supplier<Stream> objects between methods.

        My performance test (the timing numbers aren't very useful, but definitely grow with size):

        ---

        import java.util.*;
        import java.util.stream.*;

        public class StreamOptimization {

            public static void main(String... args) {
                for (int i = 100; i < 200_000_000; i = (int) (i * 1.3)) {
                    testArrayCount(i);
                    testListCount(i);
                }
            }

            public static void testListCount(int i) {
                List<Object> objs = new ArrayList<>(i);
                for (int j = 0; j < i; j++) objs.add(null);
                long start = System.currentTimeMillis();
                long count = objs.stream().count();
                long delta = System.currentTimeMillis() - start;
                System.out.println("list count=" + count + "; time=" + delta);
            }

            public static void testArrayCount(int i) {
                Object[] objs = new Object[i];
                long start = System.currentTimeMillis();
                long count = Arrays.stream(objs).count();
                long delta = System.currentTimeMillis() - start;
                System.out.println("array count=" + count + "; time=" + delta);
            }

        }

              psandoz Paul Sandoz
              dlsmith Dan Smith
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated:
                Resolved: