background
Today I received a request, which needs to be completed by modifying the code written by my former colleague. Find a place to need to change after finished, ready to self-test, found the execution speed is too slow, just look at the code, inside the loop set of loop, and then to the innermost circle inside a hair a SQL query, calculate can not see, change, change to the results of the open the floodgates, time to spend a little more, behind all these basic change about the time, Again to eliminate the cycle, can not cycle as far as possible, and then encountered the problem shown in the problem.
The code is not convenient to reveal, I wrote a test code, first talk about the general problem, basically with the following code about
List<Object> newList = new ArrayList<>();
for (Object i : oldList) {
Object o = new Object();
BeanUtils.copyProperties(i, o);
newList.add(o);
}
Copy the code
action
My first thought when I saw the code was, why not use a stream? But when I think about it, I wonder, is a stream really faster than a for loop in this requirement? So I decided to write some test code myself to try out which method was faster. The test code is as follows:
For loop code:
private static Long forLoopMethod(List<Object> oldList){
long begin = System.currentTimeMillis();
List<Object> newList = new ArrayList<>();
for (Object i : oldList) {
Object o = new Object();
BeanUtils.copyProperties(i, o);
newList.add(o);
}
return System.currentTimeMillis() - begin;
}
Copy the code
The code for the stream mode is as follows:
private static Long streamMethod(List<Object> oldList){
long begin = System.currentTimeMillis();
List<Object> collect = oldList.stream().map(i -> {
Object o = new Object();
BeanUtils.copyProperties(i, o);
return o;
}).collect(Collectors.toList());
return System.currentTimeMillis() - begin;
}
Copy the code
Test method:
public static void main(String[] args) { List<Object> oldList = new ArrayList<>(); for (int i = 0; i < 1000; i++) { oldList.add(i); } system.out. println("forLoopMethod takes time: "+ forLoopMethod(oldList)); System.out.println("streamMethod takes time: "+ streamMethod(oldList)); }Copy the code
Test environment:
Computer 8 core16thread
The JDK: 1.8
Test results:
Times \ method name | forLoopMethod | streamMethod |
---|---|---|
The first | 132 | 7 |
The 2nd | 118 | 6 |
The third time | 126 | 6 |
4 times | 115 | 5 |
The fifth time | 114 | 6 |
6 times | 121 | 5 |
The seventh | 124 | 6 |
eighth | 126 | 5 |
ninth | 118 | 5 |
10th | 114 | 6 |
Average time spent using the for loop: 120.8
Average time spent using a Stream: 5.7
conclusion
It is clear that the stream is much faster than the for loop given the current requirements.