Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Java8 Lambda expressions and flow operations     - Some of the bibliographic management tools to good use on linux (Linux)

- Zypper command for SUSE Linux package management (Linux)

- CentOS 7 hard disk expansion toss record (Linux)

- The difference Docker save and export commands (Linux)

- Linux system find command Detailed (Linux)

- The difference between statement and preparedStatement of the jdbc (Database)

- Shell script to crawl through AWR SQL Report Problems (Database)

- The Concept and Semantics of Java Memory Model (Programming)

- Ubuntu 14.04 jdk Installation and Configuration (Linux)

- XenServer Virtual Machine Installation --- first ISO image file storage expansion (Linux)

- MongoDB common optimization settings in Linux (Database)

- Hibernate learning introductory tutorial (Programming)

- CentOS 6.x and CentOS7 installation RPMforge (Linux)

- Nginx Load Balancing (standby) + Keepalived (Server)

- How to configure chroot environment in Ubuntu 14.04 (Linux)

- Linux operating system security tools of the Logs (Linux)

- How to ensure the Linux SSH login security with one-time password (Linux)

- Linux use logs to troubleshoot (Linux)

- Ubuntu Linux installation GAMIT10.6 (Linux)

- Linux - Common process the command (Linux)

  Java8 Lambda expressions and flow operations
  Add Date : 2018-11-21      
  There are many discussions about Java 8 flowing efficiency, but according to Alex Zhitnitsky test results show: stick with the traditional Java programming style --iterator and for-each loop - to achieve better performance than Java 8.

In Java 8 Lambda expressions and flow (Stream) received a warm welcome. This is by far the most exciting Java features. These new features allow the use of language to encode functional style, we can use these features to accomplish many interesting features. These features so interesting that it is considered to be unreasonable. We are skeptical, we decided to test these features.

We created a simple task: to find the maximum value from a ArrayList, will be tested more traditional way in Java 8 new ways. To be honest, the test results so I was very surprised.

Command style compared with Java 8 functional programming style

I like to go directly to the theme, so take a look at the results. To do this benchmark, we create an ArrayList, and insert a random integer 100 000, and by seven different ways to look through all of the maximum values. Implementation is divided into two groups: Java 8 introduced functional style and have been using Java command style.

This is the length of time spent in each method:

The biggest mistake is to record 0.042 parallel stream, the output at the end of a complete section of this article can be seen.


Wow! Any new way Java 8 will be available in a performance difference of about 5 times. Sometimes using a simple iterator loop is more effective than mixing lambda expressions and flow, so even need to write a few lines of code, and need to skip the sweet syntactic sugar (syntactic suger).

Iterator or for-each loop is the most effective way to traverse the ArrayList, twice as good performance than using an index value for the traditional round-robin fashion.

In Java 8, the best performance of parallel streams. But be careful, in some cases it may also cause the program to run more slowly.

Speed ​​Lambda expressions between flow and parallel flow. This result is really quite surprising, since the implementation of the lambda expression is based on the API stream to achieve.

Not all cases are as follows: when we want to demonstrate the lambda expressions and flow is very easy to make mistakes, we received a lot of feedback from the community, we are required to optimize the benchmark code, such as the elimination of integers autoloader package reconciliation package actions . The second test (optimized) results in the end of this article can be seen.

Let's quickly look at each method in accordance with the running speed from fast to slow:

Command style

iteratorMaxInteger () - using an iterator to traverse the list:

public int iteratorMaxInteger () {
    int max = Integer.MIN_VALUE;
    for (Iterator it = integers.iterator (); it.hasNext ();) {
        max = Integer.max (max, it.next ());
    return max;
forEachLoopMaxInteger () - do not use the iterator, using For-Each loop through the list (do not misuse forEach Java 8's)

public int forEachLoopMaxInteger () {
    int max = Integer.MIN_VALUE;
    for (Integer n: integers) {
        max = Integer.max (max, n);
    return max;
forMaxInteger () - using a simple for loop iterates through the list and index:

public int forMaxInteger () {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i         max = Integer.max (max, integers.get (i));
    return max;
Functional style

parallelStreamMaxInteger () - use Java 8 parallel streams traverse the list:

public int parallelStreamMaxInteger () {
    Optional max = integers.parallelStream () reduce (Integer :: max).;
    return max.get ();
lambdaMaxInteger () - the use of lambda expressions and streams traverse the list. The elegant line of code:

public int lambdaMaxInteger () {
    return integers.stream () reduce (Integer.MIN_VALUE, (a, b) -> Integer.max (a, b)).;
forEachLambdaMaxInteger () - This use case is a bit confusing. Probably because Java forEach 8 features a very annoying thing: Use only final variable, so we create a final wrapper class to solve the problem, so we will be able to access the maximum value after the update.

public int forEachLambdaMaxInteger () {
    final Wrapper wrapper = new Wrapper ();
    wrapper.inner = Integer.MIN_VALUE;
    integers.forEach (i -> helper (i, wrapper));
    return wrapper.inner.intValue ();
public static class Wrapper {
    public Integer inner;
private int helper (int i, Wrapper wrapper) {
    wrapper.inner = Math.max (i, wrapper.inner);
    return wrapper.inner;
Incidentally, if you want to discuss forEach, we have provided some interesting insights about its shortcomings, the answer see StackOverflow.

streamMaxInteger () - Use Java flow through a list of 8:

public int streamMaxInteger () {
    Optional max = integers.stream () reduce (Integer :: max).;
    return max.get ();
Benchmark optimized

Based on feedback from this article, we create another version of the benchmark. Except the source code can be viewed here. Here are the test results:

Summary of Changes:

Modified with a list of no more volatile.
New Method forMax2 remove access to member variables.
Remove forEachLambda redundant helper functions. Now lambda expression as a value to the variable. Readability decreased, but faster.
Eliminate automatic packing. If you turn on automatic packing warnings project in Eclipse, old code will be 15 warning.
Code optimization flow, before first use mapToInt reduce.
Thanks Patrick Reinhart, Richard Warburton, Yan Bonnel, Sergey Kuksenko, Jeff Maxwell, Henrik Gustafsson and Twitter comments on each person, thank you for your contribution.

Test infrastructure

We use JMH (Java Microbenchmarking Harness) implementation of the benchmark tests. If you want to know how to apply it in your own project, you can refer to this article, we own writing examples to demonstrate the main features of JMH.

Based test configuration includes two JVM, 5 times preheat iterations and five measurements iterations. The test runs on c3.xlarge Amazon EC2 instances (CPU: 4 core, memory: 7.5G, memory: 2 x 40 GB SSD), the use of Java 8u66 and JMH 1.11.2. All source code on GitHub, you can see the raw output here.

Way to do some Disclaimer: Benchmark often not fully trusted, it is difficult to guarantee absolutely correct. Although we tried in the most accurate way to run, it is recommended that a skeptical attitude to accept the results.

Final Thoughts

The first thing to start using Java 8 is to use lambda expressions and flow in practice. But remember: it is indeed very good, good enough to probably make you addicted! However, we have seen, the use of traditional and for-each iteration loop Java Java programming style is much higher than the performance of the 8 new ways.

Of course, this is not absolute. But it really is a fairly common example, it appears there may be about five times the performance gap. If that affect the core functionality of the system or to become a new bottleneck in the system, it is quite frightening.
- VMware virtual machine Ubuntu install arm-linux-gcc cross-compiler environment (Linux)
- CentOS6.6 ordinary users to use sudo command to borrow root user privileges (Linux)
- How to install Wine 1.7.20 under Ubuntu or Linux Mint (Linux)
- APT-mirror using a four-step configuration Ubuntu local depot (Linux)
- Linux file permissions bit forced bits and adventure Comments (Linux)
- Linux systems use logwatch log file monitoring (Linux)
- Python object-oriented programming (Programming)
- How to contribute code to the GNU Project (Linux)
- Java Generics (Programming)
- Windows7 / 8 / 8.1 hard drive to install Ubuntu 14.04 dual system (Linux)
- PostgreSQL use pgpool achieve high availability (Database)
- Android gets the global process information and the memory used by the process (Programming)
- Magical Virtualbox under Ubuntu (Linux)
- The three-way division of the sorting algorithm Quicksort (Programming)
- Lucene Getting Started Tutorial (Server)
- Root of AVL Tree- achieve balanced search trees AVL tree (Programming)
- Windows using SSH management Ubuntu (Linux)
- Hadoop1.2.1 plug compilation (Server)
- C ++ stderr / stdout redirected to a file (Programming)
- Use Mop monitor stock prices at the Linux command line (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.