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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With