Why is this parallel thread running 15x SLOWER?
I've tried to demonstrate Java newbie threads and the like. He said he read that streams can be slower than loops for primitive types. So, I immediately decided to prove it wrong! I was in shock!
Stream and serial stream work roughly the same, but parallel stream is serial and significantly slower. Can someone explain why?
@Test
public void foo() throws Exception {
Random r = new Random();
IntSummaryStatistics stats = new IntSummaryStatistics();
long start = System.currentTimeMillis();
for(int i = 0; i < 100000000;i++) {
stats.accept(r.nextInt() * 2);
}
System.out.println(System.currentTimeMillis() - start);
start = System.currentTimeMillis();
stats = r.ints(100000000).map(rn -> rn * 2).summaryStatistics();
System.out.println(System.currentTimeMillis() - start);
start = System.currentTimeMillis();
stats = r.ints(100000000).parallel().map(rn -> rn * 2).summaryStatistics();
System.out.println(System.currentTimeMillis() - start);
}
resutls:
1067 1047 15184
+3
source to share
No one has answered this question yet
See similar questions:
2
or similar: