Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java8 Lambda expressions and flow operations     - The method of MySQL two kinds of incomplete recovery (Database)

- Acquaintance C ++: the most simple C ++ program (Programming)

- Solaris 10 installation configuration mrtg monitoring system (Linux)

- XenServer virtual machines installed in dual-card configuration (Server)

- File upload via AngularJS and ASP.NET MVC5 (Programming)

- Android Custom View password box example (Programming)

- Add local search to your Android app (Programming)

- Row-level security and application-level solutions for the new features of PostgreSQL9.5 (Database)

- Linux administrator should command: sed and awk (Linux)

- impdp error ORA-39001, ORA-39000, ORA-31619 (Database)

- PostgreSQL procedural language learning (Database)

- Copy files between two Linux hosts (Linux)

- C # and JavaScript arrays to re-summary (Programming)

- C ++ implementation of the list of basic operations and test cases (Programming)

- MongoDB Learning the notes (Database)

- Oracle how to maintain the consistency of read? (Database)

- Binary tree traversal recursive and non-recursive (cyclic) traversal achieve (Programming)

- Swift string common method (Programming)

- PHP interview questions of design patterns (Programming)

- Linux Beginner Guide: Installing packages on Ubuntu and Fedora (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.

Tips:

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.
     
         
         
         
  More:      
 
- Ubuntu apt-mirror established local private sources (Linux)
- How to Install Cantata MPD 1.3.3 for Ubuntu and Derived Version Users (Linux)
- CentOS 6.5 three ways to configure the IP address (Linux)
- Convert MySQL date string to a NULL value exception handling (Database)
- Ubuntu 14.10 installation SecureCRT 7.3 (Linux)
- Oracle Database routine inspection (Database)
- Installation Android IDE development tools, Android Studio 1.5 under Ubuntu (Linux)
- xCAT install and update software (Linux)
- Java reflection technology explain (Programming)
- Memcached source installation and configuration under CentOS 6.6 (Server)
- Java implementation linear table - represents the order of representation and chain (Programming)
- Linux file permissions chmod chown (Linux)
- Inject script commands manually annotated summary (Linux)
- Linux cron job (Linux)
- Oracle database on the hit rate of query summary (Database)
- Fedora && Arch Linux - the most romantic thing to happen now (Linux)
- Install Web-based monitoring tool: Linux-Dash (Server)
- UNIX and class UNIX system security check notes (Linux)
- VirtualBox snapshots (Linux)
- Oracle 11g logical standby achieve BI needs (Database)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.