Java: Stream and Classic Loop – Benchmark

Java 8 has rich possibilities to process the collections. One of them is stream. The main goal of stream, as I see it, is changing of programming paradigm: from “how to do” to “what to do”. Focusing on functionality instead of writing the control operators.

I wrote a simple code to compare performance (see code on Git). This is not absolute benchmark test. I even did not try to get some absolute result. And I don’t think it is possible. I just compared two types of list with few approaches: class loop, iterator, forEach, stream with max, reduce (different implementations), with parallel.

Below are results:

Collection Method Max Duration in ms.
List for 2147450338 6
List iterator 2147450338 8
List forEach 2147450338 4
List Stream max 2147450338 6
List Stream max with parallel 2147450338 8
List Stream reduce 1 2147450338 3
List Stream reduce 1 with parallel 2147450338 4
List Stream reduce 2 2147450338 4
List Stream reduce 2 with parallel 2147450338 5
LinkedList for 2147450338 3221
LinkedList iterator 2147450338 1
List forEach 2147450338 6
LinkedList Stream max 2147450338 2
LinkedList Stream max with parallel 2147450338 3
LinkedList Stream reduce 1 2147450338 1
LinkedList Stream reduce 1 with parallel 2147450338 2
LinkedList Stream reduce 2 2147450338 1
LinkedList Stream reduce 2 with parallel 2147450338 2

Conclusion is very simple: use what is better for your needs. Streams have a lot of advantages. You may find many information about this in Internet. But for each concrete case the choice depends on type of task, type of collection, algorithm of processing etc. Sometimes usage of parallel may be very problematic.

About ysden123

We are not only for work... All my time free from work I spend on photography. Most photos are from our travels. I like make photos in still life style as well.
This entry was posted in java, Programming and tagged , , , , , . Bookmark the permalink.

1 Response to Java: Stream and Classic Loop – Benchmark

  1. Tony says:

    Interestin! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.