6

How is IntStream, DoubleStream, or LongStream better than regular stream in Java 8?

Do these threads have high performance or maybe usability?

Anton Sorokin
  • 494
  • 6
  • 23
  • I find them convenient. They have some operations that are special for numbers. I would expect that they also perform a bit better, not something I know. – Ole V.V. Feb 23 '19 at 11:07
  • @OleV.V. What operations? – Anton Sorokin Feb 23 '19 at 11:20
  • 3
    @AntonSorokin e.g. [`IntStream#summaryStatistics()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/IntStream.html#summaryStatistics()) – Turing85 Feb 23 '19 at 11:22

1 Answers1

7

Stream<Integer> etc. have to work with boxed values (Integer instead of primitive int) which takes significantly more memory and usually a lot of boxing/unboxing operations (depending on your code). Why only Int/Double/Long? Just because they were expected to be used most often.

Same applies to OptionalInt and friends and all the functional interfaces.

For collections (lists/maps/sets) there are many third-party libraries providing primitive specialization for the same reason. Really the problem there is even more acute because with streams you don't (usually; sorted() is a counter-example) need to store many values in memory.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • "with streams you don't need to store many values in memory" But what about parallel streams? Isn't their advantage in handling large amounts of data? – Anton Sorokin Feb 23 '19 at 11:19
  • Two comments: first, on `IntStream` and alike, you have [`summaryStatistics()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/IntStream.html#summaryStatistics()), which gives you easy access to statistical information like min, max, mean,.... Second, [project valhalla](https://openjdk.java.net/projects/valhalla/) aims to neglect the problem with additional object creation, although I am not convinced that this is a huge memory/performance problem overall. – Turing85 Feb 23 '19 at 11:20
  • @Turing85 True, but in a world where Java already had generics over primitives when `Stream`s were added, I'd be _very_ surprised if `IntStream` was a separate type instead of making `Streams.summaryStatistics(Stream)`. As it is, `IntStream` provides a convenient place to put it. – Alexey Romanov Feb 23 '19 at 11:26
  • @AntonSorokin Still as streams, so they don't need all elements in memory. – Alexey Romanov Feb 23 '19 at 11:31