9

Trying to wrap my head around the difference between IntStream and Stream<Integer>. I illustrate with an example below:

int[] someInts = {1, 2, 3, 4, 5};
var intStream = Arrays.stream(someInts);
var streamInteger = Arrays.stream(someInts).boxed();

What is the difference between both? And how does the difference relate to performance?

alt-f4
  • 2,112
  • 17
  • 49
  • 1
    Does this answer your question? [What is the advantage of IntStream over usual Stream?](https://stackoverflow.com/questions/54840920/what-is-the-advantage-of-intstream-over-usual-stream) – Mingwei Samuel Nov 23 '20 at 19:35

2 Answers2

14

What is the difference between both?

IntStream is a stream of primitive int values.

Stream<Integer> is a stream of Integer objects.

The list of operations available are different, just check the list of methods in the javadoc. E.g. IntStream has built-in concepts of range(...) and sum(), not that sum() is difficult to do with Stream<Integer> using reduce(), but it isn't built in.

How does the difference relate to performance?

Boxing and unboxing does take some time, but it's not a lots. A lot of temporary boxed objects also triggers Garbage Collection a lot more often, and that's a performance drain too. It all adds up, so if the stream processes a lot of integer values in a tight "loop", the difference can be relevant.

The bigger problem is space, since the overhead of Integer is quite large. An int is 4 bytes for the value, while an Integer is 4 bytes for the reference plus 16 bytes for the object, so Integer uses 20 bytes per value, i.e. 5 times the memory.

This is especially relevant if you call toArray(), since there's a big difference between an int[] and an Integer[], space-wise.

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

Stream<Integer> operates on boxed values (Integer instead of primitive int) which takes significantly more memory and usually a lot of boxing/unboxing operations (depending on your code), whereas IntStream works with primitives.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124