Java 8 nested loops with streams amp; performance(Java 8 嵌套循环与流 amp;表现)
问题描述
In order to practise the Java 8 streams I tried converting the following nested loop to the Java 8 stream API. It calculates the largest digit sum of a^b (a,b < 100) and takes ~0.135s on my Core i5 760.
My solution, which I expected to be faster because of the paralellism actually took 0.25s (0.19s without the parallel()
):
My questions
- did I do the conversion right or is there a better way to convert nested loops to stream calculations?
- why is the stream variant so much slower than the old one?
- why did the parallel() statement actually increased the time from 0.19s to 0.25s?
I know that microbenchmarks are fragile and parallelism is only worth it for big problems but for a CPU, even 0.1s is an eternity, right?
Update
I measure with the Junit 4 framework in Eclipse Kepler (it shows the time taken for executing a test).
My results for a,b<1000 instead of 100:
- traditional loop 186s
- sequential stream 193s
- parallel stream 55s
Update 2
Replacing sum+=Integer.valueOf(c+"");
with sum+= c - '0';
(thanks Peter!) shaved off 10 whole seconds of the parallel method, bringing it to 45s. Didn't expect such a big performance impact!
Also, reducing the parallelism to the number of CPU cores (4 in my case) didn't do much as it reduced the time only to 44.8s (yes, it adds a and b=0 but I think this won't impact the performance much):
I have created a quick and dirty micro benchmark based on your code. The results are:
loop: 3192
lambda: 3140
lambda parallel: 868
So the loop and lambda are equivalent and the parallel stream significantly improves the performance. I suspect your results are unreliable due to your benchmarking methodology.
I have also run it with jmh which is more reliable than manual tests. The results are consistent with above (micro seconds per call):
这篇关于Java 8 嵌套循环与流 &表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!