上一篇文章說到,對於在java8中使用stream中的並行流的幾個建議的說明。下面咱們就寫一個測試用例測量一下(在性能優化時,遵循的三個黃金規則:測量、測量、測量)java
com.kisszero.one.paralleljava.util.stream.LongStreamjava.util.stream.StreamParallelStreamsUtils { (n) { result = (i = i <= ni++) { result += i} result} (n) { Stream.(i -> i + ).limit(n).reduce(Long::).get()} (n) { Stream.(i -> i + ).limit(n).parallel().reduce(Long::).get()} (n) { LongStream.(n).reduce(Long::).getAsLong()} (n) { LongStream.(n).parallel().reduce(Long::).getAsLong()} (n) { Accumulator accumulator = Accumulator()LongStream.(n).forEach(accumulator::add)accumulator.} (n) { Accumulator accumulator = Accumulator()LongStream.(n).parallel().forEach(accumulator::add)accumulator.} Accumulator { = (value) { += value} } }
com.kisszero.one.paralleljava.util.concurrent.ForkJoinPooljava.util.function.FunctionParallelStreamsTest { ForkJoinPool = ForkJoinPool()(String[] args) { System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )} <> (Function<> finput) { fastest = Long.(i = i < i++) { start = System.()result = f.apply(input)duration = (System.() - start) / System..println(+ result)(duration < fastest) fastest = duration} fastest} } 結果: Iterative Sum done in: 5 msecs Sequential Sum done in: 154 msecs Parallel forkJoinSum done in: 376 msecs Range forkJoinSum done in: 13 msecs Parallel range forkJoinSum done in: 8 msecs SideEffect sum done in: 4 msecs Result: 22454695176953 Result: 20121132009947 Result: 16076928917786 Result: 16957805754284 Result: 13642545729260 Result: 12997343158699 Result: 13761162440338 Result: 17902422526976 Result: 21642228116467 Result: 17496039228969 SideEffect prallel sum done in: 47 msecs
Stream中的LongStream.rangClosed方法比iterate在這種求和的狀況下效率更好,由於前者直接產生原始類型的long數字,沒有裝箱拆箱的開銷,還有就是前者生成的數字範圍,很容易的拆分爲獨立的小塊。
性能優化