我比较了一个1000万整数数组中一个简单的“find max”逻辑的性能。简单的for循环比lambda和并行流版本执行得多(至少好10倍)。
有人可以帮我理解这种反直觉行为吗?我有一台安装了Windows 7专业版的四核英特尔i5处理器戴尔E5530笔记本电脑, 1.8.0_60 64位JVM 。
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
public class MaxFind
{
private static final int CAPACITY = 10_000_000;
public static void main(String[] args) throws Exception
{
List<Integer> numbers = new ArrayList<Integer>(CAPACITY);
Random rand = new Random();
long start = System.currentTimeMillis();
for(int i=0; i<CAPACITY; i++)
numbers.add(rand.nextInt());
long end = System.currentTimeMillis();
System.out.println("size of numbers: " + numbers.size() + ", time taken to populate: " + (end-start) + " milliseconds");
start = System.currentTimeMillis();
int maxNum = Integer.MIN_VALUE;
//imperative approach
for(int i=0; i<numbers.size(); i++)
maxNum = Integer.max(numbers.get(i), maxNum);
end = System.currentTimeMillis();
System.out.println("Time taken to find the max value " + maxNum + " using normal for loop: " + (end-start) + " milliseconds.");
start = System.currentTimeMillis();
//lambda, parallel stream
Optional<Integer> max = numbers.parallelStream().reduce(Integer::max);
end = System.currentTimeMillis();
System.out.println("Time taken to find the max value " + max.get() + " using lambda with parallel stream 1: " + (end-start) + " milliseconds.");
start = System.currentTimeMillis();
maxNum = numbers.parallelStream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
end = System.currentTimeMillis();
System.out.println("Time taken to find the max value " + max.get() + " using lambda with parallel stream 2: " + (end-start) + " milliseconds.");
}
}