We have had a quick
overview of Java 8 Streams API in the last post. We looked into the
Power and simplicity of the Java 8 Streams API, brief about the
Intermediate and the Terminal Operations over the streams, and different
ways of building the streams (e.g from collections or numerical ranges
etc.). In continuation to the same discussion, in this post, we will
move ahead with the streams and have a look at the most important
property of Java 8 Streams that is Laziness. If you are new to the concept of Java 8 streams, please go back and read Understanding Java 8 Streams API.
Laziness Improves Performance (?):This is really a tricky question. If the laziness is utilized in a right manner, the answer is 'yes'. Consider you are on an online shopping site and you searched for a particular type of a product. Usually most of the websites will show few of the matching products immediately and a 'loading more' message at the bottom. Finally, all of the search results will be loaded in parts, as described. The intent behind doing this is to keep the user interested by immediately showing him some of the results. While the user is browsing through the loaded products, the rest of the products are being loaded. This is because, the site is delaying the complete loading of the entire product list. Consider, if the site does eager loading or early loading of all of the products, the response time would increase and the user might get distracted to something else.
While you are dealing with bigger data, or infinite streams the laziness is a real boon. When the data is processed, we are not sure how the processed data will be used. The eager processing will always process the entire amount of data at the cost of performance and client might end up utilizing very small chunk of it, or depending upon some condition, client may not even need to utilize that data. The lazy processing is based on 'process only on demand' strategy.
Laziness and Java 8 Streams:
The current era is all about Big Data, Parallel Processing, and Being Real Time. Large number of systems are being re-designed to sustain in the future challenges of the consistently growing amount of data, and high expectations of the performance and scalability. No wonder, if the processing model of the Java Collections API is being empowered in order to meet the future expectations. The Java 8 Streams API is fully based on the 'process only on demand' strategy and hence supports laziness.
In the Java 8 Streams API, the intermediate operations are lazy and their internal processing model is optimized to make it being capable of processing the large amount of data with high performance.
The original post can be read at Java 8 Streams API - Laziness and Performance Optimization: