转:http://www.importnew.com/17262.html
有许许多多关于 Java 8 中流效率的讨论,但根据 Alex Zhitnitsky 的测试结果显示:坚持使用传统的 Java 编程风格——iterator 和 for-each 循环——比 Java 8 的实现性能更佳。
开始使用 Java 8 的第一件事情是在实践中使用 lambda 表达式和流。但是请记住:它确实非常好,好到可能会让你上瘾!但是,我们也看到了,使用传统迭代器和 for-each 循环的 Java 编程风格比 Java 8 中的新方式性能高很多。
当然,这也不是绝对的。但这确实是一个相当常见的例子,它显示可能会有大约 5 倍的性能差距。如果这影响到系统的核心功能或成为系统一个新的瓶颈,那就相当可怕了。
例子:
我们先创建了一个 ArrayList,并插入一个 100000 个随机整数,并通过 7 种不同的方式遍历所有的值来查找最大值
lambda比foreach效率慢5倍
使用迭代器遍历列表:
public int iteratorMaxInteger() {
int max = Integer.MIN_VALUE;
for (Iterator it = integers.iterator(); it.hasNext(); ) {
max = Integer.max(max, it.next());
}
return max;
}
使用 For-Each 循环遍历列表:
public int forEachLoopMaxInteger() {
int max = Integer.MIN_VALUE;
for (Integer n : integers) {
max = Integer.max(max, n);
}
return max;
}
使用简单的for循环:
public int forMaxInteger() {
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
max = Integer.max(max, integers.get(i));
}
return max;
}
使用java8并行流:
public int parallelStreamMaxInteger() {
Optional max = integers.parallelStream().reduce(Integer::max);
return max.get();
}
使用 lambda 表达式及流:
public int lambdaMaxInteger() {
return integers.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
}