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.