轉: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)); }