I have two functions solving the same problem. The first uses a sequential stream, and the second uses a parallel stream.
public static int digitalRoot(int n) {
int sum = String.valueOf(n).chars().map(i -> Integer.parseInt(String.valueOf((char) i))).sum();
if (sum >= 10) {
return digitalRoot(sum);
} else {
return sum;
}
}
public static int digitalRootParallel(int n) {
int sum = String.valueOf(n).chars().parallel().
map(i -> Integer.parseInt(String.valueOf((char) i))).sum();
if (sum >= 10) {
return digitalRootParallel(sum);
} else {
return sum;
}
}
I executed these functions once. The parallel function digitalRootParallel() was faster (5 ms) than the sequential (32 ms) digitalRoot().
But when I executed each of them in a loop of 1.000.000, the sequential (117 ms) was faster than the parallel (1124 ms).
for (int i = 0; i < 1000000; i++) {
sum = digitalRoot(n);
}
Why is the loop with the parallel stream slower?